home *** CD-ROM | disk | FTP | other *** search
/ Games of Daze / Infomagic - Games of Daze (Summer 1995) (Disc 1 of 2).iso / x2ftp / msdos / png / png10txt / png10.txt < prev   
Encoding:
Text File  |  1995-05-06  |  120.2 KB  |  2,823 lines

  1. PNG (Portable Network Graphics) Specification,
  2. **********************************************
  3. Tenth Draft
  4. ***********
  5.  
  6. Revision date: 5 May, 1995 
  7.  
  8.  Copyright 1995, Thomas Boutell. Permission is granted to
  9.  reproduce this specification in complete and unaltered form.
  10.  Excerpts may be printed with the following notice: "excerpted
  11.  from the PNG (Portable Network Graphics) specification, tenth
  12.  draft." No notice is required in software that follows this
  13.  specification; notice is only required when reproducing or
  14.  excerpting from the specification itself. 
  15.  
  16. Contents
  17. ========
  18.  
  19.  o 0. Status 
  20.  o 1. Introduction 
  21.  o 2. Data Representation 
  22.     o Integers and byte order 
  23.     o Color values 
  24.     o Image layout 
  25.     o Alpha channel 
  26.     o Filtering 
  27.     o Interlaced data order 
  28.     o Gamma correction 
  29.     o Text strings 
  30.  o 3. File Structure 
  31.     o PNG file signature 
  32.     o Chunk layout 
  33.     o Chunk naming conventions 
  34.     o CRC algorithm 
  35.  o 4. Chunk Specifications 
  36.     o Critical Chunks 
  37.     o Ancillary Chunks 
  38.     o Summary of Standard Chunks 
  39.     o Additional Chunk Types 
  40.  o 5. Deflate/Inflate Compression 
  41.  o 6. Filter Algorithms 
  42.     o Filter type 0: None 
  43.     o Filter type 1: Sub 
  44.     o Filter type 2: Up 
  45.     o Filter type 3: Average 
  46.     o Filter type 4: Paeth 
  47.  o 7. Chunk Ordering Rules 
  48.  o 8. Multi-Image Extension 
  49.  o 9. Recommendations for Encoders 
  50.     o Bitdepth scaling 
  51.     o Encoder gamma handling 
  52.     o Alpha channel creation 
  53.     o Filter selection 
  54.     o Text chunk processing 
  55.     o Registering proprietary chunks 
  56.  o 10. Recommendations for Decoders 
  57.     o Chunk error checking 
  58.     o Pixel dimensions 
  59.     o Truecolor image handling 
  60.     o Decoder gamma handling 
  61.     o Background color 
  62.     o Alpha channel processing 
  63.     o Progressive display 
  64.     o Palette histogram usage 
  65.     o Text chunk processing 
  66.  o 11. Appendix: Rationale 
  67.     o Why a new file format? 
  68.     o Why these features? 
  69.     o Why not these features? 
  70.     o Why not use format XYZ? 
  71.     o Byte order 
  72.     o Interlacing 
  73.     o Why gamma encoding? 
  74.     o Non-premultiplied alpha 
  75.     o Filtering 
  76.     o Text strings 
  77.     o PNG file signature 
  78.     o Chunk layout 
  79.     o Chunk naming conventions 
  80.     o Palette histograms 
  81.  o 12. Appendix: Sample CRC Code 
  82.  o 13. Credits 
  83.  
  84. 0. Status
  85. =========
  86.  
  87. This is the tenth draft of the PNG specification. All future drafts will be
  88. backward-compatible with the graphics file format described by this
  89. document. Implementations are invited, and a reference
  90. implementation is under development; see below. 
  91.  
  92. Archive sites
  93. =============
  94.  
  95. The latest versions of this document and related information can always
  96. be found at the PNG FTP archive site, 
  97. ftp.uu.net:/graphics/png/. The maintainers of the PNG
  98. specification can be contacted by e-mail at 
  99. png-info@uunet.uu.net. 
  100.  
  101. At present, this document is available on the World Wide Web from 
  102. http://sunsite.unc.edu/boutell/png.html, but this
  103. location may not be as permanent as the ones above. 
  104.  
  105. Changes since draft 9
  106. =====================
  107.  
  108.  o Extensive editing 
  109.  o Clarified interlaced representation of very small images: no filter
  110.    bytes are present in an empty pass 
  111.  o Chunk ordering rules clarified 
  112.  o Limits set on tEXt chunk keyword length 
  113.  o cHRM chunk description corrected: CIE x and y, not X and Y 
  114.  o More extensive explanation of alpha and gamma processing 
  115.  o Separate document created for extension chunk types 
  116.  o Permanent archive site and e-mail contact point established 
  117.  
  118. Reference implementation
  119. ========================
  120.  
  121. It is anticipated that a reference implementation will be available
  122. before the end of May 1995. The reference implementation will be
  123. freely usable in all applications, including commercial applications. 
  124.  
  125. When finished, the reference implementation will be available from the
  126. PNG FTP archive site, ftp.uu.net:/graphics/png/. 
  127.  
  128. A set of test images will also be prepared and will be available from the
  129. same site. 
  130.  
  131. 1. Introduction
  132. ===============
  133.  
  134. The PNG format is intended to provide a portable, legally
  135. unencumbered, well-compressed, well-specified standard for lossless
  136. bitmapped image files. 
  137.  
  138. Although the initial motivation for developing PNG was to replace GIF,
  139. the design provides some useful new features not available in GIF, with
  140. minimal cost to developers. 
  141.  
  142. GIF features retained in PNG include: 
  143.  
  144.  o Palette-mapped images of up to 256 colors. 
  145.  o Streamability: files can be read and written strictly serially, thus
  146.    allowing the file format to be used as a communications protocol
  147.    for on-the-fly generation and display of images. 
  148.  o Progressive display: a suitably prepared image file can be
  149.    displayed as it is received over a communications link, yielding a
  150.    low-resolution image very quickly with gradual improvement of
  151.    detail thereafter. 
  152.  o Transparency: portions of the image can be marked as
  153.    transparent, allowing the effect of a nonrectangular image area
  154.    to be achieved. 
  155.  o Ancillary information: textual comments and other data can be
  156.    stored within the image file. 
  157.  o Complete hardware and platform independence. 
  158.  o Effective, 100% lossless compression. 
  159.  
  160. Important new features of PNG, not available in GIF, include: 
  161.  
  162.  o Truecolor images of up to 48 bits per pixel. 
  163.  o Grayscale images of up to 16 bits per pixel. 
  164.  o Full alpha channel (general transparency masks). 
  165.  o Image gamma indication, allowing automatic
  166.    brightness/contrast adjustment. 
  167.  o Reliable, straightforward detection of file corruption. 
  168.  o Faster initial presentation in progressive display mode. 
  169.  
  170. PNG is intended to be: 
  171.  
  172.  o Simple and portable: PNG should be widely implementable with
  173.    reasonably small effort for developers. 
  174.  o Legally unencumbered: to the best of the knowledge of the PNG
  175.    authors, no algorithms under legal challenge are used. 
  176.  o Well compressed: both palette-mapped and truecolor images are
  177.    compressed as effectively as in any other widely used lossless
  178.    format, and in most cases more effectively. 
  179.  o Interchangeable: any standard-conforming PNG decoder will
  180.    read all conforming PNG files. 
  181.  o Flexible: the format allows for future extensions and private
  182.    add-ons, without compromising interchangeability of basic
  183.    PNG. 
  184.  o Robust: the design supports full file integrity checking as well as
  185.    simple, quick detection of common transmission errors. 
  186.  
  187. The main part of this specification simply gives the definition of the file
  188. format. An appendix gives the rationale for many design decisions.
  189. Although the rationale is not part of the formal specification, reading it
  190. may help implementors to understand the design. Cross-references in
  191. the main text point to relevant parts of the rationale. 
  192.  
  193. See Rationale: Why a new file format?, Why these features?, Why not
  194. these features?, Why not use format XYZ?. 
  195.  
  196. Pronunciation
  197. =============
  198.  
  199. PNG is pronounced "ping". 
  200.  
  201. 2. Data Representation
  202. ======================
  203.  
  204. This chapter discusses basic data representations used in PNG files, as
  205. well as the expected representation of the image data. 
  206.  
  207. Integers and byte order
  208. =======================
  209.  
  210. All integers that require more than one byte will be in network byte
  211. order, which is to say the most significant byte comes first, then the less
  212. significant bytes in descending order of significance (MSB LSB for
  213. two-byte integers, B3 B2 B1 B0 for four-byte integers). The highest bit
  214. (value 128) of a byte is numbered bit 7; the lowest bit (value 1) is
  215. numbered bit 0. Values are unsigned unless otherwise noted. Values
  216. explicitly noted as signed are represented in two's complement notation.
  217.  
  218. See Rationale: Byte order. 
  219.  
  220. Color values
  221. ============
  222.  
  223. All color values range from zero (representing black) to most intense at
  224. the maximum value for the bit depth. Color values may represent either
  225. grayscale or RGB color data. Note that the maximum value at a given
  226. bit depth is not 2^bitdepth, but rather (2^bitdepth)-1. Intensity is not
  227. necessarily linear; the gAMA chunk specifies the gamma characteristic
  228. of the source device, and viewers are strongly encouraged to properly
  229. compensate. See Gamma correction, below. 
  230.  
  231. Source data with a precision not directly supported in PNG (for
  232. example, 5 bit/sample truecolor) must be scaled up to the next higher
  233. supported bit depth. Such scaling is reversible and hence incurs no loss of
  234. data, while it reduces the number of cases that decoders must cope with.
  235. See Recommendations for Encoders: Bitdepth scaling. 
  236.  
  237. Image layout
  238. ============
  239.  
  240. PNG images are laid out as a rectangular pixel array, with pixels
  241. appearing left-to-right within each scanline, and scanlines appearing
  242. top-to-bottom. (For progressive display purposes, the data may not
  243. actually be transmitted in this order; see Interlaced data order.) The size
  244. of each pixel is determined by the bit depth, which is the number of bits
  245. per stored value in the image data. 
  246.  
  247. Three types of pixels are supported: 
  248.  
  249.  o Palette-mapped pixels are represented by a single value that is
  250.    an index into a supplied palette. The bit depth determines the
  251.    maximum number of palette entries, not the color precision
  252.    within the palette. 
  253.  o Grayscale pixels are represented by a single value that is a
  254.    grayscale level, where zero is black and the largest value for the
  255.    bit depth is white. 
  256.  o Truecolor pixels are represented by three-value sequences: red
  257.    (zero = black, max = red) appears first, then green (zero = black,
  258.    max = green), then blue (zero = black, max = blue). The bit depth
  259.    specifies the size of each value, not the total pixel size. 
  260.  
  261. Optionally, grayscale and truecolor pixels can also include an alpha
  262. value, as described in the next section. 
  263.  
  264. In all cases, pixels are packed into scanlines consecutively, without
  265. wasted space between pixels. (The allowable bit depths are restricted so
  266. that the packing is simple and efficient.) When pixels are less than 8 bits
  267. deep, they are packed into bytes with the leftmost pixel in the
  268. high-order bits of a byte, the rightmost in the low-order bits. 
  269.  
  270. However, scanlines always begin on byte boundaries. When pixels are
  271. less than 8 bits deep, if the scanline width is not evenly divisible by the
  272. number of pixels per byte then the low-order bits in the last byte of each
  273. scanline are wasted. The contents of the padding bits added to fill out
  274. the last byte of a scanline are unspecified. 
  275.  
  276. An additional "filter" byte is added to the beginning of every scanline,
  277. as described in detail below. The filter byte is not considered part of the
  278. image data, but it is included in the data stream sent to the compression
  279. step. 
  280.  
  281. Alpha channel
  282. =============
  283.  
  284. An alpha channel, representing transparency levels on a per-pixel
  285. basis, may be included in grayscale and truecolor PNG images. 
  286.  
  287. An alpha channel value of 0 represents full transparency, and a value of
  288. (2^bitdepth)-1 represents a fully opaque pixel. Intermediate values
  289. indicate partially transparent pixels that may be combined with a
  290. background image to yield a composite image. 
  291.  
  292. Alpha channels may be included with images that have either 8 or 16
  293. bits per sample, but not with images that have fewer than 8 bits per
  294. sample. Alpha values are represented with the same bit depth used for
  295. the image values. The alpha value is stored immediately following the
  296. grayscale or RGB values of the pixel. 
  297.  
  298. The color stored for a pixel is not affected by the alpha value assigned to
  299. the pixel. This rule is sometimes called "unassociated" or "non
  300. premultiplied" alpha. (Another common technique is to store pixel
  301. values premultiplied by the alpha fraction; in effect, the image is already
  302. composited against a black background. PNG does not use premultiplied
  303. alpha.) 
  304.  
  305. Transparency control is also possible without the storage cost of a full
  306. alpha channel. In a palette image, an alpha value may be defined for
  307. each palette entry. In grayscale and truecolor images, a single pixel
  308. value may be identified as being "transparent". These techniques are
  309. controlled by the tRNS ancillary chunk type. 
  310.  
  311. If no alpha channel nor tRNS chunk is present, all pixels in the image
  312. are to be treated as fully opaque. 
  313.  
  314. Viewers may support transparency control partially, or not at all. 
  315.  
  316. See Rationale: Non-premultiplied alpha, Recommendations for
  317. Encoders: Alpha channel creation, and Recommendations for
  318. Decoders: Alpha channel processing. 
  319.  
  320. Filtering
  321. =========
  322.  
  323. PNG allows the image data to be filtered before it is compressed. The
  324. purpose of filtering is to improve the compressibility of the data. The
  325. filter step itself does not reduce the size of the data. All PNG filters are
  326. strictly lossless. 
  327.  
  328. PNG defines several different filter algorithms, including "none" which
  329. indicates no filtering. The filter algorithm is specified for each scanline
  330. by a filter type byte which precedes the filtered scanline in the
  331. precompression data stream. An intelligent encoder may switch filters
  332. from one scanline to the next. The method for choosing which filter to
  333. employ is up to the encoder. 
  334.  
  335. See Filter Algorithms and Rationale: Filtering. 
  336.  
  337. Interlaced data order
  338. =====================
  339.  
  340. A PNG image can be stored in interlaced order to allow progressive
  341. display. The purpose of this feature is to allow images to "fade in" when
  342. they are being displayed on-the-fly. Interlacing slightly expands the file
  343. size on average, but it gives the user a meaningful display much more
  344. rapidly. Note that decoders are required to be able to read interlaced
  345. images, whether or not they actually perform progressive display. 
  346.  
  347. With interlace type 0, pixels are stored sequentially from left to right,
  348. and scanlines sequentially from top to bottom (no interlacing). 
  349.  
  350. Interlace type 1, known as Adam7 after its author, Adam M. Costello,
  351. consists of seven distinct passes over the image. Each pass transmits a
  352. subset of the pixels in the image. The pass in which each pixel is
  353. transmitted is defined by replicating the following 8-by-8 pattern over
  354. the entire image, starting at the upper left corner: 
  355.  
  356. 1 6 4 6 2 6 4 6
  357. 7 7 7 7 7 7 7 7
  358. 5 6 5 6 5 6 5 6
  359. 7 7 7 7 7 7 7 7
  360. 3 6 4 6 3 6 4 6
  361. 7 7 7 7 7 7 7 7
  362. 5 6 5 6 5 6 5 6
  363. 7 7 7 7 7 7 7 7
  364.  
  365. Within each pass, the selected pixels are transmitted left to right within
  366. a scanline, and selected scanlines sequentially from top to bottom. For
  367. example, pass 2 contains pixels 4, 12, 20, etc. of scanlines 0, 8, 16, etc.
  368. (numbering from 0,0 at the upper left corner). The last pass contains the
  369. entirety of scanlines 1, 3, 5, etc. 
  370.  
  371. The data within each pass is laid out as though it were a complete
  372. image of the appropriate dimensions. For example, if the complete
  373. image is 8x8 pixels, then pass 3 will contain a single scanline containing
  374. two pixels. When pixels are less than 8 bits deep, each such scanline is
  375. padded to fill an integral number of bytes (see Image layout). Filtering is
  376. done on this reduced image in the usual way, and a filter type byte is
  377. transmitted before each of its scanlines (see Filter Algorithms). Notice
  378. that the transmission order is defined so that all the scanlines
  379. transmitted in a pass will have the same number of pixels; this is
  380. necessary for proper application of some of the filters. 
  381.  
  382. Caution: If the image contains fewer than five columns or fewer than
  383. five rows, some passes will be entirely empty. Encoder and decoder
  384. authors must be careful to handle this case correctly. In particular, filter
  385. bytes are only associated with nonempty scanlines; no filter bytes are
  386. present in an empty pass. 
  387.  
  388. See Rationale: Interlacing and Recommendations for Decoders: 
  389. Progressive display. 
  390.  
  391. Gamma correction
  392. ================
  393.  
  394. Gamma is a way of defining the brightness reproduction curve of a
  395. camera or display device. When brightness levels are expressed as
  396. fractions in the range 0 to 1, such a device produces an output brightness
  397. level "obright" from an input brightness level "ibright" according
  398. to the equation 
  399.  
  400.   obright = ibright ^ gamma
  401.  
  402. PNG images may specify the gamma of the camera (or simulated
  403. camera) that produced the image, and thus the gamma of the image
  404. with respect to the original scene. To get accurate tone reproduction, the
  405. gamma of the display device and the gamma of the image file should be
  406. reciprocals of each other, since the overall gamma of the system is the
  407. product of the gammas of each component. So, for example, if an image
  408. with a gamma of 0.4 is displayed on a CRT with a gamma of 2.5, the
  409. overall gamma of the system is 1.0. An overall gamma of 1.0 gives
  410. correct tone reproduction. 
  411.  
  412. In practice, images of gamma around 1.0 and gamma around 0.45 are
  413. both widely found. PNG expects encoders to record the gamma if
  414. known, and it expects decoders to correct the image gamma if necessary
  415. for proper display on their display hardware. Failure to correct for
  416. image gamma leads to a too-dark or too-light display. 
  417.  
  418. Gamma correction is not applied to the alpha channel, if any. Alpha
  419. values always represent a linear fraction of full opacity. 
  420.  
  421. See Rationale: Why gamma encoding?, Recommendations for
  422. Encoders: Encoder gamma handling, and Recommendations for
  423. Decoders: Decoder gamma handling. 
  424.  
  425. Text strings
  426. ============
  427.  
  428. A PNG file can store text associated with the image, such as an image
  429. description or copyright notice. Keywords are used to indicate what each
  430. text string represents. 
  431.  
  432. ISO 8859-1 (Latin-1) is the character set recommended for use in text
  433. strings. This character set is a superset of 7-bit ASCII. Files defining the
  434. character set may be obtained from the PNG FTP archives, 
  435. ftp.uu.net:/graphics/png/. 
  436.  
  437. Character codes not defined in Latin-1 may be used, but are unlikely to
  438. port across platforms correctly. (For that matter, any characters beyond
  439. 7-bit ASCII will not display correctly on all platforms; but Latin-1
  440. represents a set which is widely portable.) 
  441.  
  442. Provision is also made for the storage of compressed text. 
  443.  
  444. See Rationale: Text strings. 
  445.  
  446. 3. File Structure
  447. =================
  448.  
  449. A PNG file consists of a PNG signature followed by a series of chunks.
  450. This chapter defines the signature and the basic properties of chunks.
  451. Individual chunk types are discussed in the next chapter. 
  452.  
  453. PNG file signature
  454. ==================
  455.  
  456. The first eight bytes of a PNG file always contain the following
  457. (decimal) values: 
  458.  
  459. 137 80 78 71 13 10 26 10 
  460.  
  461. This signature indicates that the remainder of the file contains a single
  462. PNG image, consisting of a series of chunks beginning with an IHDR
  463. chunk and ending with an IEND chunk. 
  464.  
  465. See Rationale: PNG file signature. 
  466.  
  467. Chunk layout
  468. ============
  469.  
  470. Each chunk consists of four parts: 
  471.  
  472. Length 
  473.    A 4-byte unsigned integer giving the number of bytes in the
  474.    chunk's data field. The length counts only the data field, not
  475.    itself, the chunk type code, or the CRC. Zero is a valid length.
  476.    Although encoders and decoders should treat the length as
  477.    unsigned, its value may not exceed (2^31)-1 bytes. 
  478. Chunk Type 
  479.    A 4-byte chunk type code. For convenience in description and
  480.    in examining PNG files, type codes are restricted to consist of
  481.    uppercase and lowercase ASCII letters (A-Z, a-z). However,
  482.    encoders and decoders should treat the codes as fixed binary
  483.    values, not character strings. For example, it would not be
  484.    correct to represent the type code IDAT by the EBCDIC
  485.    equivalents of those letters. Additional naming conventions for
  486.    chunk types are discussed in the next section. 
  487. Chunk Data 
  488.    The data bytes appropriate to the chunk type, if any. This field
  489.    may be of zero length. 
  490. CRC 
  491.    A 4-byte CRC (Cyclical Redundancy Check) calculated on the
  492.    preceding bytes in that chunk, including the chunk type code
  493.    and chunk data fields, but not including the length field. The
  494.    CRC is always present, even for empty chunks such as IEND.
  495.    The CRC algorithm is specified below. 
  496.  
  497. The chunk data length may be any number of bytes up to the maximum;
  498. therefore, implementors may not assume that chunks are aligned on any
  499. boundaries larger than bytes. 
  500.  
  501. Chunks may appear in any order, subject to the restrictions placed on
  502. each chunk type. (One notable restriction is that IHDR must appear
  503. first and IEND must appear last; thus the IEND chunk serves as an
  504. end-of-file marker.) Multiple chunks of the same type may appear, but
  505. only if specifically permitted for that type. 
  506.  
  507. See Rationale: Chunk layout. 
  508.  
  509. Chunk naming conventions
  510. ========================
  511.  
  512. Chunk type codes are assigned in such a way that a decoder can
  513. determine some properties of a chunk even if it does not recognize the
  514. type code. These rules are intended to allow safe, flexible extension of
  515. the PNG format, by allowing a decoder to decide what to do when it
  516. encounters an unknown chunk. The naming rules are not normally of
  517. interest when a decoder does recognize the chunk's type. 
  518.  
  519. Four bits of the type code, namely bit 5 (value 32) of each byte, are used
  520. to convey chunk properties. This choice means that a human can read
  521. off the assigned properties according to whether each letter of the type
  522. code is uppercase (bit 5 is 0) or lowercase (bit 5 is 1). However, decoders
  523. should test the properties of an unknown chunk by numerically testing
  524. the specified bits; testing whether a character is uppercase or lowercase
  525. is inefficient, and even incorrect if a locale-specific case definition is
  526. used. 
  527.  
  528. It is also worth noting that the property bits are an inherent part of the
  529. chunk name, and hence are fixed for any chunk type. Thus, TEXT and 
  530. Text are completely unrelated chunk type codes. Decoders should
  531. recognize codes by simple four-byte literal comparison; it is incorrect to
  532. perform case conversion on type codes. 
  533.  
  534. The semantics of the property bits are: 
  535.  
  536. First Byte: 0 (uppercase) = critical, 1 (lowercase) = ancillary 
  537.    Chunks which are not strictly necessary in order to meaningfully
  538.    display the contents of the file are known as "ancillary" chunks.
  539.    Decoders encountering an unknown chunk in which the
  540.    ancillary bit is 1 may safely ignore the chunk and proceed to
  541.    display the image. The time chunk (tIME) is an example of an
  542.    ancillary chunk. 
  543.  
  544.    Chunks which are critical to the successful display of the file's
  545.    contents are called "critical" chunks. Decoders encountering an
  546.    unknown chunk in which the ancillary bit is 0 must indicate to
  547.    the user that the image contains information they cannot safely
  548.    interpret. The image header chunk (IHDR) is an example of a
  549.    critical chunk. 
  550.  
  551. Second Byte: 0 (uppercase) = public, 1 (lowercase) = private 
  552.    If the chunk is public (part of this specification or a later edition
  553.    of this specification), its second letter is uppercase. If your
  554.    application requires proprietary chunks, and you have no interest
  555.    in seeing the software of other vendors recognize them, use a
  556.    lowercase second letter in the chunk name. Such names will
  557.    never be assigned in the official specification. Note that there is
  558.    no need for software to test this property bit; it simply ensures
  559.    that private and public chunk names will not conflict. 
  560.  
  561. Third Byte: reserved, must be 0 (uppercase) always 
  562.    The significance of the case of the third letter of the chunk name
  563.    is reserved for possible future expansion. At the present time all
  564.    chunk names must have uppercase third letters. 
  565.  
  566. Fourth Byte: 0 (uppercase) = unsafe to copy, 1 (lowercase) = safe to copy 
  567.    This property bit is not of interest to pure decoders, but it is
  568.    needed by PNG editors (programs that modify a PNG file). 
  569.  
  570.    If a chunk's safe-to-copy bit is 1, the chunk may be copied to a
  571.    modified PNG file whether or not the software recognizes the
  572.    chunk type, and regardless of the extent of the file modifications.
  573.  
  574.    If a chunk's safe-to-copy bit is 0, it indicates that the chunk
  575.    depends on the image data. If the program has made any
  576.    changes to critical chunks, including addition, modification,
  577.    deletion, or reordering of critical chunks, then unrecognized
  578.    unsafe chunks must not be copied to the output PNG file. (Of
  579.    course, if the program does recognize the chunk, it may choose
  580.    to output an appropriately modified version.) 
  581.  
  582.    A PNG editor is always allowed to copy all unrecognized chunks
  583.    if it has only added, deleted, or modified ancillary chunks. This
  584.    implies that it is not permissible to make ancillary chunks that
  585.    depend on other ancillary chunks. 
  586.  
  587.    PNG editors that do not recognize a critical chunk must report
  588.    an error and refuse to process that PNG file at all. The
  589.    safe/unsafe mechanism is intended for use with ancillary chunks.
  590.    The safe-to-copy bit will always be 0 for critical chunks. 
  591.  
  592.    Rules for PNG editors are discussed further under Chunk
  593.    Ordering Rules. 
  594.  
  595. For example, the hypothetical chunk type name "bLOb" has the
  596. property bits: 
  597.  
  598.     bLOb  <-- 32 bit Chunk Name represented in ASCII form
  599.     ||||
  600.     |||'- Safe to copy bit is 1 (lower case letter; bit 5 of byte is 1)
  601.     ||'-- Reserved bit is 0     (upper case letter; bit 5 of byte is 0)
  602.     |'--- Private bit is 0      (upper case letter; bit 5 of byte is 0)
  603.     '---- Ancillary bit is 1    (lower case letter; bit 5 of byte is 1)
  604.  
  605. Therefore, this name represents an ancillary, public, safe-to-copy
  606. chunk. 
  607.  
  608. See Rationale: Chunk naming conventions. 
  609.  
  610. CRC algorithm
  611. =============
  612.  
  613. Chunk CRCs are calculated using standard CRC methods with pre and
  614. post conditioning. The CRC polynomial employed is as follows: 
  615.  
  616. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1
  617.  
  618. The 32-bit CRC register is initialized to all 1's, and then the data from
  619. each byte is processed from the least significant bit (1) to the most
  620. significant bit (128). After all the data bytes are processed, the CRC
  621. register is inverted (its ones complement is taken). This value is
  622. transmitted (stored in the file) MSB first. For the purpose of separating
  623. into bytes and ordering, the least significant bit of the 32-bit CRC is
  624. defined to be the coefficient of the x^31 term. 
  625.  
  626. Practical calculation of the CRC always employs a precalculated table
  627. to greatly accelerate the computation. See Appendix: Sample CRC
  628. Code. 
  629.  
  630. 4. Chunk Specifications
  631. =======================
  632.  
  633. This chapter defines the standard types of PNG chunks. 
  634.  
  635. Critical Chunks
  636. ===============
  637.  
  638. All implementations must understand and successfully render the
  639. standard critical chunks. A valid PNG image must contain an IHDR
  640. chunk, one or more IDAT chunks, and an IEND chunk. 
  641.  
  642. IHDR Image Header 
  643.    This chunk must appear FIRST. Its contents are: 
  644.  
  645.    Width:            4 bytes
  646.    Height:           4 bytes
  647.    Bit depth:        1 byte
  648.    Color type:       1 byte 
  649.    Compression type: 1 byte
  650.    Filter type:      1 byte
  651.    Interlace type:   1 byte
  652.  
  653.    Width and height give the image dimensions in pixels. They are
  654.    4-byte integers. Zero is an invalid value. The maximum for each
  655.    is (2^31)-1 in order to accommodate languages which have
  656.    difficulty with unsigned 4-byte values. 
  657.  
  658.    Bit depth is a single-byte integer giving the number of bits per
  659.    pixel (for palette images) or per sample (for grayscale and
  660.    truecolor images). Valid values are 1, 2, 4, 8, and 16, although
  661.    not all values are allowed for all color types. 
  662.  
  663.    Color type is a single-byte integer that describes the
  664.    interpretation of the image data. Color type values represent
  665.    sums of the following values: 1 (palette used), 2 (color used), and
  666.    4 (full alpha used). Valid values are 0, 2, 3, 4, and 6. 
  667.  
  668.    Bit depth restrictions for each color type are imposed both to
  669.    simplify implementations and to prohibit certain combinations
  670.    that do not compress well in practice. Decoders must support all
  671.    legal combinations of bit depth and color type. (Note that bit
  672.    depths of 16 are easily supported on 8-bit display hardware by
  673.    dropping the least significant byte.) The allowed combinations
  674.    are: 
  675.  
  676.    Color    Allowed    Interpretation
  677.    Type    Bit Depths
  678.  
  679.    0       1,2,4,8,16  Each pixel value is a grayscale level.
  680.  
  681.    2       8,16        Each pixel value is an R,G,B series.
  682.  
  683.    3       1,2,4,8     Each pixel value is a palette index;
  684.                        a PLTE chunk must appear.
  685.  
  686.    4       8,16        Each pixel value is a grayscale level,
  687.                        followed by an alpha channel level.
  688.  
  689.    6       8,16        Each pixel value is an R,G,B series,
  690.                        followed by an alpha channel level.
  691.  
  692.    Compression type is a single-byte integer that indicates the
  693.    method used to compress the image data. At present, only
  694.    compression type 0 (deflate/inflate compression with a 32K
  695.    sliding window) is defined. All standard PNG images must be
  696.    compressed with this scheme. The compression type code is
  697.    provided for possible future expansion or proprietary variants.
  698.    Decoders must check this byte and report an error if it holds an
  699.    unrecognized code. See Deflate/Inflate Compression for details. 
  700.  
  701.    Filter type is a single-byte integer that indicates the
  702.    preprocessing method applied to the image data before
  703.    compression. At present, only filter type 0 (adaptive filtering
  704.    with five basic filter types) is defined. As with the compression
  705.    type code, decoders must check this byte and report an error if it
  706.    holds an unrecognized code. See Filter Algorithms for details. 
  707.  
  708.    Interlace type is a single-byte integer that indicates the
  709.    transmission order of the pixel data. Two values are currently
  710.    defined: 0 (no interlace) or 1 (Adam7 interlace). See Interlaced
  711.    data order for details. 
  712.  
  713. PLTE Palette 
  714.    This chunk's contents are from 1 to 256 palette entries, each a
  715.    three-byte series of the form: 
  716.  
  717.    red:   1 byte (0 = black, 255 = red)
  718.    green: 1 byte (0 = black, 255 = green)
  719.    blue:  1 byte (0 = black, 255 = blue)
  720.  
  721.    The number of entries is determined from the chunk length. A
  722.    chunk length not divisible by 3 is an error. 
  723.  
  724.    This chunk must appear for color type 3, and may appear for
  725.    color types 2 and 6. If this chunk does appear, it must precede the
  726.    first IDAT chunk. There cannot be more than one PLTE chunk. 
  727.  
  728.    For color type 3 (palette data), the PLTE chunk is required. The
  729.    first entry in PLTE is referenced by pixel value 0, the second by
  730.    pixel value 1, etc. The number of palette entries must not exceed
  731.    the range that can be represented by the bit depth (for example,
  732.    2^4 = 16 for a bit depth of 4). It is permissible to have fewer
  733.    entries than the bit depth would allow. In that case, any
  734.    out-of-range pixel value found in the image data is an error. 
  735.  
  736.    For color types 2 and 6 (truecolor), the PLTE chunk is optional.
  737.    If present, it provides a recommended set of from 1 to 256 colors
  738.    to which the truecolor image may be quantized if the viewer
  739.    cannot display truecolor directly. If PLTE is not present, such a
  740.    viewer must select colors on its own, but it is often preferable for
  741.    this to be done once by the encoder. 
  742.  
  743.    Note that the palette uses 8 bits (1 byte) per value regardless of
  744.    the image bit depth specification. In particular, the palette is 8
  745.    bits deep even when it is a suggested quantization of a 16-bit
  746.    truecolor image. 
  747.  
  748. IDAT Image Data 
  749.    This chunk contains the actual image data. To create this data,
  750.    begin with image scanlines represented as described under Image
  751.    layout; the layout and total size of this raw data are determinable
  752.    from the IHDR fields. Then filter the image data according to
  753.    the filtering method specified by the IHDR chunk. (Note that
  754.    with filter method 0, the only one currently defined, this implies
  755.    prepending a filter type byte to each scanline.) Finally, compress
  756.    the filtered data using the compression method specified by the 
  757.    IHDR chunk. The IDAT chunk contains the output datastream
  758.    of the compression algorithm. To read the image data, reverse
  759.    this process. 
  760.  
  761.    There may be multiple IDAT chunks; if so, they must appear
  762.    consecutively with no other intervening chunks. The compressed
  763.    datastream is then the concatenation of the contents of all the 
  764.    IDAT chunks. The encoder may divide the compressed data
  765.    stream into IDAT chunks as it wishes. (Multiple IDAT chunks
  766.    are allowed so that encoders can work in a fixed amount of
  767.    memory; typically the chunk size will correspond to the encoder's
  768.    buffer size.) It is important to emphasize that IDAT chunk
  769.    boundaries have no semantic significance and can appear at any
  770.    point in the compressed datastream. A PNG file in which each 
  771.    IDAT chunk contains only one data byte is legal, though
  772.    remarkably wasteful of space. (For that matter, zero-length 
  773.    IDAT chunks are legal, though even more wasteful.) 
  774.  
  775.    See Filter Algorithms and Deflate/Inflate Compression for
  776.    details. 
  777.  
  778. IEND Image Trailer 
  779.    This chunk must appear LAST. It marks the end of the PNG
  780.    data stream. The chunk's data field is empty. 
  781.  
  782. Ancillary Chunks
  783. ================
  784.  
  785. All ancillary chunks are optional, in the sense that encoders need not
  786. write them and decoders may ignore them. However, encoders are
  787. encouraged to write the standard ancillary chunks when the
  788. information is available, and decoders are encouraged to interpret these
  789. chunks when appropriate and feasible. 
  790.  
  791. The standard ancillary chunks are listed in alphabetical order. This is
  792. not necessarily the order in which they would appear in a file. 
  793.  
  794. bKGD Background Color 
  795.    This chunk specifies a default background color against which
  796.    the image may be presented. Note that viewers are not bound to
  797.    honor this chunk; a viewer may choose to use a different
  798.    background color. 
  799.  
  800.    For color type 3 (palette), the bKGD chunk contains: 
  801.  
  802.    palette index: 1 byte
  803.  
  804.    The value is the palette index of the color to be used as
  805.    background. 
  806.  
  807.    For color types 0 and 4 (grayscale, with or without alpha), bKGD
  808.    contains: 
  809.  
  810.    gray:  2 bytes, range 0 .. (2^bitdepth) - 1
  811.  
  812.    (For consistency, 2 bytes are used regardless of the image bit
  813.    depth.) The value is the gray level to be used as background. 
  814.  
  815.    For color types 2 and 6 (RGB, with or without alpha), bKGD
  816.    contains: 
  817.  
  818.    red:   2 bytes, range 0 .. (2^bitdepth) - 1
  819.    green: 2 bytes, range 0 .. (2^bitdepth) - 1
  820.    blue:  2 bytes, range 0 .. (2^bitdepth) - 1
  821.  
  822.    (For consistency, 2 bytes per sample are used regardless of the
  823.    image bit depth.) This is the RGB color to be used as background.
  824.  
  825.    When present, the bKGD chunk must precede the first IDAT
  826.    chunk, and must follow the PLTE chunk, if any. 
  827.  
  828.    See Recommendations for Decoders: Background color. 
  829.  
  830. cHRM Primary Chromaticities and White Point 
  831.    Applications that need precise specification of colors in a PNG
  832.    file may use this chunk to specify the chromaticities of the red,
  833.    green, and blue primaries used in the image, and the referenced
  834.    white point. These values are based on the 1931 CIE
  835.    (International Color Committee) XYZ color space. Only the
  836.    chromaticities (x and y) are specified. The chunk layout is: 
  837.  
  838.    White Point x: 4 bytes
  839.    White Point y: 4 bytes
  840.    Red x:         4 bytes
  841.    Red y:         4 bytes
  842.    Green x:       4 bytes
  843.    Green y:       4 bytes
  844.    Blue x:        4 bytes
  845.    Blue y:        4 bytes
  846.  
  847.    Each value is encoded as a 4-byte unsigned integer, representing
  848.    the x or y value times 100000. 
  849.  
  850.    If the cHRM chunk appears, it must precede the first IDAT
  851.    chunk, and it must also precede the PLTE chunk if present. 
  852.  
  853. gAMA Gamma Correction 
  854.    The gamma correction chunk specifies the gamma of the
  855.    camera (or simulated camera) that produced the image, and
  856.    thus the gamma of the image with respect to the original scene.
  857.    Note that this is not the same as the gamma of the display device
  858.    that will reproduce the image correctly. 
  859.  
  860.    The chunk's contents are: 
  861.  
  862.    Image gamma value: 4 bytes
  863.  
  864.    A value of 100000 represents a gamma of 1.0, a value of 45000 a
  865.    gamma of 0.45, and so on (divide by 100000.0). Values around
  866.    1.0 and around 0.45 are common in practice. 
  867.  
  868.    If the encoder does not know the gamma value, it should not
  869.    write a gamma chunk; the absence of a gamma chunk indicates
  870.    the gamma is unknown. 
  871.  
  872.    If the gAMA chunk appears, it must precede the first IDAT
  873.    chunk, and it must also precede the PLTE chunk if present. 
  874.  
  875.    See Gamma correction, Recommendations for Encoders: 
  876.    Encoder gamma handling, and Recommendations for Decoders: 
  877.    Decoder gamma handling. 
  878.  
  879. hIST Image Histogram 
  880.    The histogram chunk gives the approximate usage frequency of
  881.    each color in the color palette. A histogram chunk may appear
  882.    only when a palette chunk appears. If a viewer is unable to
  883.    provide all the colors listed in the palette, the histogram may
  884.    help it decide how to choose a subset of the colors for display. 
  885.  
  886.    This chunk's contents are a series of 2-byte (16 bit) unsigned
  887.    integers. There must be exactly one entry for each entry in the 
  888.    PLTE chunk. Each entry is proportional to the fraction of pixels
  889.    in the image that have that palette index; the exact scale factor
  890.    is chosen by the encoder. 
  891.  
  892.    Histogram entries are approximate, with the exception that a
  893.    zero entry specifies that the corresponding palette entry is not
  894.    used at all in the image. It is required that a histogram entry be
  895.    nonzero if there are any pixels of that color. 
  896.  
  897.    When the palette is a suggested quantization of a truecolor
  898.    image, the histogram is necessarily approximate, since a decoder
  899.    may map pixels to palette entries differently than the encoder
  900.    did. In this situation, zero entries should not appear. 
  901.  
  902.    The hIST chunk, if it appears, must follow the PLTE chunk, and
  903.    must precede the first IDAT chunk. 
  904.  
  905.    See Rationale: Palette histograms, and Recommendations for
  906.    Decoders: Palette histogram usage. 
  907.  
  908. pHYs Physical Pixel Dimensions 
  909.    This chunk specifies the intended resolution for display of the
  910.    image. The chunk's contents are: 
  911.  
  912.    4 bytes: pixels per unit, X axis (unsigned integer)
  913.    4 bytes: pixels per unit, Y axis (unsigned integer)
  914.    1 byte: unit specifier
  915.  
  916.    The following values are legal for the unit specifier: 
  917.  
  918.    0: unit is unknown (pHYs defines pixel aspect ratio only)
  919.    1: unit is the meter 
  920.  
  921.    Conversion note: one inch is equal to exactly 0.0254 meters. 
  922.  
  923.    If this ancillary chunk is not present, pixels are assumed to be
  924.    square, and the physical size of each pixel is unknown. 
  925.  
  926.    If present, this chunk must precede the first IDAT chunk. 
  927.  
  928.    See Recommendations for Decoders: Pixel dimensions. 
  929.  
  930. sBIT Significant Bits 
  931.    To simplify decoders, PNG specifies that only certain bit depth
  932.    values be used, and further specifies that pixel values must be
  933.    scaled to the full range of possible values at that bit depth.
  934.    However, the sBIT chunk is provided in order to store the
  935.    original number of significant bits, since this information may be
  936.    of use to some decoders. We recommend that an encoder emit an
  937.    sBIT chunk if it has converted the data from a different bit
  938.    depth. 
  939.  
  940.    For color type 0 (grayscale), the sBIT chunk contains a single
  941.    byte, indicating the number of bits which were significant in the
  942.    source data. 
  943.  
  944.    For color type 2 (RGB truecolor), the sBIT chunk contains
  945.    three bytes, indicating the number of bits which were significant
  946.    in the source data for the red, green, and blue channels,
  947.    respectively. 
  948.  
  949.    For color type 3 (palette color), the sBIT chunk contains three
  950.    bytes, indicating the number of bits which were significant in the
  951.    source data for the red, green, and blue components of the
  952.    palette entries, respectively. 
  953.  
  954.    For color type 4 (grayscale with alpha channel), the sBIT chunk
  955.    contains two bytes, indicating the number of bits which were
  956.    significant in the source grayscale data and the source alpha
  957.    channel data, respectively. 
  958.  
  959.    For color type 6 (RGB truecolor with alpha channel), the sBIT
  960.    chunk contains four bytes, indicating the number of bits which
  961.    were significant in the source data for the red, green, blue and
  962.    alpha channels, respectively. 
  963.  
  964.    Note that sBIT does not have any implications for the
  965.    interpretation of the stored image: the bit depth indicated by 
  966.    IHDR is the correct depth. sBIT is only an indication of the
  967.    history of the image. However, an sBIT chunk showing a bit
  968.    depth less than the IHDR bit depth does mean that not all
  969.    possible color values occur in the image; this fact may be of use to
  970.    some decoders. 
  971.  
  972.    If the sBIT chunk appears, it must precede the first IDAT
  973.    chunk, and it must also precede the PLTE chunk if present. 
  974.  
  975. tEXt Textual Data 
  976.    Any textual information that the encoder wishes to record with
  977.    the image is stored in tEXt chunks. Each tEXt chunk contains
  978.    a keyword and a text string, in the format: 
  979.  
  980.    Keyword:        n bytes (character string)
  981.    Null separator: 1 byte
  982.    Text:           n bytes (character string)
  983.  
  984.    The keyword and text string are separated by a zero byte (null
  985.    character). Neither the keyword nor the text string may contain
  986.    a null character. Note that the text string is not null-terminated
  987.    (the length of the chunk is sufficient information to locate the
  988.    ending). The keyword must be at least one character and less
  989.    than 80 characters long. The text string may be of any length
  990.    from zero bytes up to the maximum permissible chunk size. 
  991.  
  992.    Any number of tEXt chunks may appear, and more than one
  993.    with the same keyword is permissible. 
  994.  
  995.    The keyword indicates the type of information represented by
  996.    the text string. The following keywords are predefined and
  997.    should be used where appropriate: 
  998.  
  999.    Title            Short (one line) title or caption for image
  1000.    Author           Name of image's creator
  1001.    Copyright        Copyright notice
  1002.    Description      Description of image (possibly long)
  1003.    Software         Software used to create the image
  1004.    Disclaimer       Legal disclaimer
  1005.    Warning          Warning of nature of content
  1006.    Source           Device used to create the image
  1007.    Comment          Miscellaneous comment; conversion from GIF comment
  1008.  
  1009.    Other keywords, containing any sequence of printable characters
  1010.    in the character set, may be invented for other purposes.
  1011.    Keywords of general interest may be registered with the
  1012.    maintainers of the PNG specification. 
  1013.  
  1014.    Keywords must be spelled exactly as registered, so that decoders
  1015.    may use simple literal comparisons when looking for particular
  1016.    keywords. In particular, keywords are considered case-sensitive. 
  1017.  
  1018.    Both keyword and text are interpreted according to the ISO
  1019.    8859-1 (Latin-1) character set. Newlines in the text string
  1020.    should be represented by a single linefeed character (decimal
  1021.    10); use of other ASCII control characters is discouraged. 
  1022.  
  1023.    See Recommendations for Encoders: Text chunk processing and
  1024.    Recommendations for Decoders: Text chunk processing. 
  1025.  
  1026. tIME Image Last-Modification Time 
  1027.    This chunk gives the time of the last image modification (not the
  1028.    time of initial image creation). The chunk contents are: 
  1029.  
  1030.    2 bytes: Year (complete; for example, 1995, not 95)
  1031.    1 byte: Month (1-12)
  1032.    1 byte: Day (1-31)
  1033.    1 byte: Hour (0-23)
  1034.    1 byte: Minute (0-59)
  1035.    1 byte: Second (0-60)    (yes, 60, for leap seconds; not 61, a common error)
  1036.  
  1037.    Universal Time (UTC, also called GMT) should be specified
  1038.    rather than local time. 
  1039.  
  1040. tRNS Transparency 
  1041.    Transparency is an alternative to the full alpha channel.
  1042.    Although transparency is not as elegant as the full alpha
  1043.    channel, it requires less storage space and is sufficient for many
  1044.    common cases. 
  1045.  
  1046.    For color type 3 (palette), this chunk's contents are a series of
  1047.    alpha channel bytes, corresponding to entries in the PLTE
  1048.    chunk: 
  1049.  
  1050.    Alpha for palette index 0:  1 byte
  1051.    Alpha for palette index 1:  1 byte
  1052.    etc.
  1053.  
  1054.    Each entry indicates that pixels of that palette index should be
  1055.    treated as having the specified alpha value. Alpha values have
  1056.    the same interpretation as in an 8-bit full alpha channel: 0 is
  1057.    fully transparent, 255 is fully opaque, regardless of image bit
  1058.    depth. The tRNS chunk may contain fewer alpha channel bytes
  1059.    than there are palette entries. In this case, the alpha channel
  1060.    value for all remaining palette entries is assumed to be 255. In
  1061.    the common case where only palette index 0 need be made
  1062.    transparent, only a one-byte tRNS chunk is needed. The tRNS
  1063.    chunk may not contain more bytes than there are palette entries.
  1064.  
  1065.    For color type 0 (grayscale), the tRNS chunk contains a single
  1066.    gray level value, stored in the format 
  1067.  
  1068.    gray:  2 bytes, range 0 .. (2^bitdepth) - 1
  1069.  
  1070.    (For consistency, 2 bytes are used regardless of the image bit
  1071.    depth.) Pixels of the specified gray level are to be treated as
  1072.    transparent (equivalent to alpha value 0); all other pixels are to
  1073.    be treated as fully opaque (alpha value (2^bitdepth)-1). 
  1074.  
  1075.    For color type 2 (RGB), the tRNS chunk contains a single RGB
  1076.    color value, stored in the format 
  1077.  
  1078.    red:   2 bytes, range 0 .. (2^bitdepth) - 1
  1079.    green: 2 bytes, range 0 .. (2^bitdepth) - 1
  1080.    blue:  2 bytes, range 0 .. (2^bitdepth) - 1
  1081.  
  1082.    (For consistency, 2 bytes per sample are used regardless of the
  1083.    image bit depth.) Pixels of the specified color value are to be
  1084.    treated as transparent (equivalent to alpha value 0); all other
  1085.    pixels are to be treated as fully opaque (alpha value
  1086.    (2^bitdepth)-1). 
  1087.  
  1088.    tRNS is prohibited for color types 4 and 6, since a full alpha
  1089.    channel is already present in those cases. 
  1090.  
  1091.    Note: when dealing with 16-bit grayscale or RGB data, it is
  1092.    important to compare both bytes of the sample values to
  1093.    determine whether a pixel is transparent. Although decoders
  1094.    may drop the low-order byte of the samples for display, this must
  1095.    not occur until after the data has been tested for transparency.
  1096.    For example, if the grayscale level 0x0001 is specified to be
  1097.    transparent, it would be incorrect to compare only the
  1098.    high-order byte and decide that 0x0002 is also transparent. 
  1099.  
  1100.    When present, the tRNS chunk must precede the first IDAT
  1101.    chunk, and must follow the PLTE chunk, if any. 
  1102.  
  1103. zTXt Compressed Textual Data 
  1104.    A zTXt chunk contains textual data, just as tEXt does;
  1105.    however, zTXt takes advantage of compression. 
  1106.  
  1107.    A zTXt chunk begins with an uncompressed Latin-1 keyword
  1108.    followed by a null (0) character, just as in the tEXt chunk. The
  1109.    next byte after the null contains a compression type byte, for
  1110.    which the only presently legitimate value is zero (deflate/inflate
  1111.    compression). The compression-type byte is followed by a
  1112.    compressed data stream which makes up the remainder of the
  1113.    chunk. Decompression of this data stream yields Latin-1 text
  1114.    which is equivalent to the text stored in a tEXt chunk. 
  1115.  
  1116.    Any number of zTXt and tEXt chunks may appear in the same
  1117.    file. See the preceding definition of the tEXt chunk for the
  1118.    predefined keywords and the exact format of the text. 
  1119.  
  1120.    See Deflate/Inflate Compression, Recommendations for
  1121.    Encoders: Text chunk processing, and Recommendations for
  1122.    Decoders: Text chunk processing. 
  1123.  
  1124. Summary of Standard Chunks
  1125. ==========================
  1126.  
  1127. This table summarizes some properties of the standard chunk types. 
  1128.  
  1129. Critical chunks (must appear in this order, except PLTE is optional):
  1130.  
  1131.         Name  Multiple  Ordering constraints
  1132.                 OK?
  1133.  
  1134.         IHDR    No      Must be first
  1135.         PLTE    No      Before IDAT
  1136.         IDAT    Yes     Multiple IDATs must be consecutive
  1137.         IEND    No      Must be last
  1138.  
  1139. Ancillary chunks (need not appear in this order):
  1140.  
  1141.         Name  Multiple  Ordering constraints
  1142.                 OK?
  1143.  
  1144.         cHRM    No      Before PLTE and IDAT
  1145.         gAMA    No      Before PLTE and IDAT
  1146.         sBIT    No      Before PLTE and IDAT
  1147.         bKGD    No      After PLTE; before IDAT
  1148.         hIST    No      After PLTE; before IDAT
  1149.         tRNS    No      After PLTE; before IDAT
  1150.         pHYs    No      Before IDAT
  1151.         tIME    No      None
  1152.         tEXt    Yes     None
  1153.         zTXt    Yes     None
  1154.  
  1155. Standard keywords for tEXt and zTXt chunks: 
  1156.  
  1157. Title            Short (one line) title or caption for image
  1158. Author           Name of image's creator
  1159. Copyright        Copyright notice
  1160. Description      Description of image (possibly long)
  1161. Software         Software used to create the image
  1162. Disclaimer       Legal disclaimer
  1163. Warning          Warning of nature of content
  1164. Source           Device used to create the image
  1165. Comment          Miscellaneous comment; conversion from GIF comment
  1166.  
  1167. Additional Chunk Types
  1168. ======================
  1169.  
  1170. Additional public PNG chunk types are defined in the document "PNG
  1171. Special-Purpose Public Chunks", available by FTP from 
  1172. ftp.uu.net:/graphics/png/ or via WWW from 
  1173. http://sunsite.unc.edu/boutell/pngextensions.html.
  1174.  
  1175. Chunks described there are expected to be somewhat less widely
  1176. supported than those defined in this specification. However, application
  1177. authors are encouraged to use those chunk types whenever appropriate
  1178. for their applications. Additional chunk types may be proposed for
  1179. inclusion in that list by contacting the PNG specification maintainers at
  1180. png-info@uunet.uu.net. 
  1181.  
  1182. Decoders must treat unrecognized chunk types as described under 
  1183. Chunk naming conventions. 
  1184.  
  1185. 5. Deflate/Inflate Compression
  1186. ==============================
  1187.  
  1188. PNG compression type 0 (the only compression method presently
  1189. defined for PNG) specifies deflate/inflate compression with a 32K
  1190. window. Deflate compression is an LZ77 derivative used in zip, gzip,
  1191. pkzip and related programs. Extensive research has been done
  1192. supporting its patent-free status. Portable C implementations are freely
  1193. available. 
  1194.  
  1195. Documentation and C code for deflate are available from the Info-Zip
  1196. archives at ftp.uu.net:/pub/archiving/zip/. 
  1197.  
  1198. Deflate-compressed datastreams within PNG are stored in the "zlib"
  1199. format, which has the structure: 
  1200.  
  1201. Compression method/flags code: 1 byte
  1202. Additional flags/check bits:   1 byte
  1203. Compressed data blocks:        n bytes
  1204. Checksum:                      4 bytes
  1205.  
  1206. Further details on this format may be found in the zlib specification. At
  1207. this writing, the zlib specification is at draft 3.1, and is available from 
  1208. ftp.uu.net:/pub/archiving/zip/doc/zlib-3.1.doc. 
  1209.  
  1210. For PNG compression type 0, the zlib compression method/flags code
  1211. must specify method code 8 ("deflate" compression) and an LZ77
  1212. window size of not more than 32K. 
  1213.  
  1214. The checksum stored at the end of the zlib datastream is calculated on
  1215. the uncompressed data represented by the datastream. Note that the
  1216. algorithm used is not the same as the CRC calculation used for PNG
  1217. chunk checksums. Verifying the chunk CRCs provides adequate
  1218. confidence that the PNG file has been transmitted undamaged. The zlib
  1219. checksum is useful mainly as a crosscheck that the deflate and inflate
  1220. algorithms are implemented correctly. 
  1221.  
  1222. The compressed data within the zlib datastream is stored as a series of
  1223. blocks, each of which can represent raw (uncompressed) data,
  1224. LZ77-compressed data encoded with fixed Huffman codes, or
  1225. LZ77-compressed data encoded with custom Huffman codes. A marker
  1226. bit in the final block identifies it as the last block, allowing the decoder
  1227. to recognize the end of the compressed datastream. Further details on
  1228. the compression algorithm and the encoding may be found in the
  1229. deflate specification. At this writing, the deflate specification is at draft
  1230. 1.1, and is available from 
  1231. ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc.
  1232.  
  1233. In a PNG file, the concatenation of the contents of all the IDAT chunks
  1234. makes up a zlib datastream as specified above. This datastream
  1235. decompresses to filtered image data as described elsewhere in this
  1236. document. 
  1237.  
  1238. It is important to emphasize that the boundaries between IDAT chunks
  1239. are arbitrary and may fall anywhere in the zlib datastream. There is not
  1240. necessarily any correlation between IDAT chunk boundaries and deflate
  1241. block boundaries or any other feature of the zlib data. For example, it is
  1242. entirely possible for the terminating zlib checksum to be split across 
  1243. IDAT chunks. 
  1244.  
  1245. In the same vein, there is no required correlation between the structure
  1246. of the image data (i.e., scanline boundaries) and deflate block
  1247. boundaries or IDAT chunk boundaries. The complete image data is
  1248. represented by a single zlib datastream that is stored in some number of 
  1249. IDAT chunks; a decoder that assumes any more than this is incorrect.
  1250. (Of course, a particular encoder implementation may happen to emit
  1251. files in which some of these structures are in fact related. But decoders
  1252. may not rely on this.) 
  1253.  
  1254. PNG also uses zlib datastreams in zTXt chunks. In a zTXt chunk, the
  1255. remainder of the chunk following the compression type code byte is a
  1256. zlib datastream as specified above. This datastream decompresses to the
  1257. user-readable text described by the chunk's keyword. Unlike the image
  1258. data, such datastreams are not split across chunks; each zTXt chunk
  1259. contains an independent zlib datastream. 
  1260.  
  1261. 6. Filter Algorithms
  1262. ====================
  1263.  
  1264. This chapter describes the pixel filtering algorithms which may be
  1265. applied in advance of compression. The purpose of these filters is to
  1266. prepare the image data for optimum compression. 
  1267.  
  1268. PNG defines five basic filtering algorithms, which are given numeric
  1269. codes as follows: 
  1270.  
  1271. Code    Name
  1272. 0       None
  1273. 1       Sub
  1274. 2       Up
  1275. 3       Average
  1276. 4       Paeth
  1277.  
  1278. The encoder may choose which algorithm to apply on a
  1279. scanline-by-scanline basis. In the image data sent to the compression
  1280. step, each scanline is preceded by a filter type byte containing the
  1281. numeric code of the filter algorithm used for that scanline. 
  1282.  
  1283. Filtering algorithms are applied to bytes, not to pixels, regardless of the
  1284. bit depth or color type of the image. The filtering algorithms work on
  1285. the byte sequence formed by a scanline that has been represented as
  1286. described under Image layout. 
  1287.  
  1288. When the image is interlaced, each pass of the interlace pattern is
  1289. treated as an independent image for filtering purposes. The filters work
  1290. on the byte sequences formed by the pixels actually transmitted during a
  1291. pass, and the "previous scanline" is the one previously transmitted in the
  1292. same pass, not the one adjacent in the complete image. Note that the
  1293. subimage transmitted in any one pass is always rectangular, but is of
  1294. smaller width and/or height than the complete image. Filtering is not
  1295. applied when this subimage is empty. 
  1296.  
  1297. For all filters, the bytes "to the left of" the first pixel in a scanline must
  1298. be treated as being zero. For filters that refer to the prior scanline, the
  1299. entire prior scanline must be treated as being zeroes for the first scanline
  1300. of an image (or of a pass of an interlaced image). 
  1301.  
  1302. To reverse the effect of a filter, the decoder must use the decoded values
  1303. of the prior pixel on the same line, the pixel immediately above the
  1304. current pixel on the prior line, and the pixel just to the left of the pixel
  1305. above. This implies that at least one scanline's worth of image data must
  1306. be stored by the decoder at all times. Even though some filter types do
  1307. not refer to the prior scanline, the decoder must always store each
  1308. scanline as it is decoded, since the next scanline might use a filter that
  1309. refers to it. 
  1310.  
  1311. PNG imposes no restriction on which filter types may be applied to an
  1312. image. However, the filters are not equally effective on all types of data.
  1313. See Recommendations for Encoders: Filter selection. 
  1314.  
  1315. See also Rationale: Filtering. 
  1316.  
  1317. Filter type 0: None
  1318. ===================
  1319.  
  1320. With the None filter, the scanline is transmitted unmodified; it is only
  1321. necessary to insert a filter type byte before the data. 
  1322.  
  1323. Filter type 1: Sub
  1324. ==================
  1325.  
  1326. The Sub filter transmits the difference between each byte and the value
  1327. of the corresponding byte of the prior pixel. 
  1328.  
  1329. To compute the Sub filter, apply the following formula to each byte of
  1330. each scanline: 
  1331.  
  1332.   Sub(x) = Raw(x) - Raw(x-bpp)
  1333.  
  1334. where x ranges from zero to the number of bytes representing that
  1335. scanline minus one, Raw(x) refers to the raw data byte at that byte
  1336. position in the scanline, and bpp is defined as the number of bytes per
  1337. complete pixel, rounding up to one. For example, for color type 2 with a
  1338. bit depth of 16, bpp is equal to 6 (three channels, two bytes per channel);
  1339. for color type 0 with a bit depth of 2, bpp is equal to 1 (rounding up); for
  1340. color type 4 with a bit depth of 16, bpp is equal to 4 (two-byte grayscale
  1341. value, plus two-byte alpha channel). 
  1342.  
  1343. Note this computation is done for each byte, regardless of bit depth. In a
  1344. 16-bit image, MSBs are differenced from the preceding MSB and LSBs
  1345. are differenced from the preceding LSB, because of the way that bpp is
  1346. defined. 
  1347.  
  1348. Unsigned arithmetic modulo 256 is used, so that both the inputs and
  1349. outputs fit into bytes. The sequence of Sub values is transmitted as the
  1350. filtered scanline. 
  1351.  
  1352. For all x < 0, assume Raw(x) = 0. 
  1353.  
  1354. To reverse the effect of the Sub filter after decompression, output the
  1355. following value: 
  1356.  
  1357.   Sub(x) + Raw(x-bpp)
  1358.  
  1359. (computed mod 256), where Raw refers to the bytes already decoded. 
  1360.  
  1361. Filter type 2: Up
  1362. =================
  1363.  
  1364. The Up filter is just like the Sub filter except that the pixel immediately
  1365. above the current pixel, rather than just to its left, is used as the
  1366. predictor. 
  1367.  
  1368. To compute the Up filter, apply the following formula to each byte of
  1369. each scanline: 
  1370.  
  1371.   Up(x) = Raw(x) - Prior(x)
  1372.  
  1373. where x ranges from zero to the number of bytes representing that
  1374. scanline minus one, Raw(x) refers to the raw data byte at that byte
  1375. position in the scanline, and Prior(x) refers to the unfiltered bytes of
  1376. the prior scanline. 
  1377.  
  1378. Note this is done for each byte, regardless of bit depth. Unsigned
  1379. arithmetic modulo 256 is used, so that both the inputs and outputs fit
  1380. into bytes. The sequence of Up values is transmitted as the filtered
  1381. scanline. 
  1382.  
  1383. On the first scanline of an image (or of a pass of an interlaced image),
  1384. assume Prior(x) = 0 for all x. 
  1385.  
  1386. To reverse the effect of the Up filter after decompression, output the
  1387. following value: 
  1388.  
  1389.   Up(x) + Prior(x)
  1390.  
  1391. (computed mod 256), where Prior refers to the decoded bytes of the
  1392. prior scanline. 
  1393.  
  1394. Filter type 3: Average
  1395. ======================
  1396.  
  1397. The Average filter uses the average of the two neighboring pixels (left
  1398. and above) to predict the value of a pixel. 
  1399.  
  1400. To compute the Average filter, apply the following formula to each byte
  1401. of each scanline: 
  1402.  
  1403.   Average(x) = Raw(x) - floor((Raw(x-bpp)+Prior(x))/2)
  1404.  
  1405. where x ranges from zero to the number of bytes representing that
  1406. scanline minus one, Raw(x) refers to the raw data byte at that byte
  1407. position in the scanline, Prior(x) refers to the unfiltered bytes of the
  1408. prior scanline, and bpp is defined as for the Sub filter. 
  1409.  
  1410. Note this is done for each byte, regardless of bit depth. The sequence of 
  1411. Average values is transmitted as the filtered scanline. 
  1412.  
  1413. The subtraction of the predicted value from the raw byte must be done
  1414. modulo 256, so that both the inputs and outputs fit into bytes. However,
  1415. the sum Raw(x-bpp)+Prior(x) must be formed without overflow
  1416. (using at least nine-bit arithmetic). floor() indicates that the result
  1417. of the division is rounded to the next lower integer if fractional; in other
  1418. words, it is an integer division or right shift operation. 
  1419.  
  1420. For all x < 0, assume Raw(x) = 0. On the first scanline of an image (or of
  1421. a pass of an interlaced image), assume Prior(x) = 0 for all x. 
  1422.  
  1423. To reverse the effect of the Average filter after decompression, output
  1424. the following value: 
  1425.  
  1426.   Average(x) + floor((Raw(x-bpp)+Prior(x))/2)
  1427.  
  1428. where the result is computed mod 256, but the prediction is calculated in
  1429. the same way as for encoding. Raw refers to the bytes already decoded,
  1430. and Prior refers to the decoded bytes of the prior scanline. 
  1431.  
  1432. Filter type 4: Paeth
  1433. ====================
  1434.  
  1435. The Paeth filter computes a simple linear function of the three
  1436. neighboring pixels (left, above, upper left), then chooses as predictor the
  1437. neighboring pixel closest to the computed value. This technique is taken
  1438. from Alan W. Paeth's article "Image File Compression Made Easy" in
  1439. Graphics Gems II, James Arvo, editor, Academic Press, 1991. 
  1440.  
  1441. To compute the Paeth filter, apply the following formula to each byte of
  1442. each scanline: 
  1443.  
  1444.   Paeth(x) = Raw(x) - PaethPredictor(Raw(x-bpp),Prior(x),Prior(x-bpp))
  1445.  
  1446. where x ranges from zero to the number of bytes representing that
  1447. scanline minus one, Raw(x) refers to the raw data byte at that byte
  1448. position in the scanline, Prior(x) refers to the unfiltered bytes of the
  1449. prior scanline, and bpp is defined as for the Sub filter. 
  1450.  
  1451. Note this is done for each byte, regardless of bit depth. Unsigned
  1452. arithmetic modulo 256 is used, so that both the inputs and outputs fit
  1453. into bytes. The sequence of Paeth values is transmitted as the filtered
  1454. scanline. 
  1455.  
  1456. The PaethPredictor function is defined by the following pseudocode: 
  1457.  
  1458.      function PaethPredictor (a, b, c)
  1459.      begin
  1460.           ; a = left, b = above, c = upper left
  1461.           p := a + b - c        ; initial estimate
  1462.           pa := abs(p - a)      ; distances to a, b, c
  1463.           pb := abs(p - b)
  1464.           pc := abs(p - c)
  1465.           ; return nearest of a,b,c,
  1466.           ; breaking ties in order a,b,c.
  1467.           if pa <= pb AND pa <= pc 
  1468.           begin
  1469.                return a
  1470.           end
  1471.           if pb <= pc
  1472.           begin
  1473.                return b
  1474.           end
  1475.           return c
  1476.      end
  1477.  
  1478. The calculations within the PaethPredictor function must be performed
  1479. exactly, without overflow. Arithmetic modulo 256 is to be used only for
  1480. the final step of subtracting the function result from the target pixel
  1481. value. 
  1482.  
  1483. Note that the order in which ties are broken is fixed and must not be
  1484. altered. The tie break order is: pixel to the left, pixel above, pixel to the
  1485. upper left. (This order differs from that given in Paeth's article.) 
  1486.  
  1487. For all x < 0, assume Raw(x) = 0 and Prior(x) = 0. On the first scanline
  1488. of an image (or of a pass of an interlaced image), assume Prior(x) = 0
  1489. for all x. 
  1490.  
  1491. To reverse the effect of the Paeth filter after decompression, output the
  1492. following value: 
  1493.  
  1494.   Paeth(x) + PaethPredictor(Raw(x-bpp),Prior(x),Prior(x-bpp))
  1495.  
  1496. (computed mod 256), where Raw and Prior refer to bytes already
  1497. decoded. Exactly the same PaethPredictor function is used by both
  1498. encoder and decoder. 
  1499.  
  1500. 7. Chunk Ordering Rules
  1501. =======================
  1502.  
  1503. To allow new chunk types to be added to PNG, it is necessary to establish
  1504. rules about the ordering requirements for all chunk types. Otherwise a
  1505. PNG editing program cannot know what to do when it encounters an
  1506. unknown chunk. 
  1507.  
  1508. We define a "PNG editor" as a program that modifies a PNG file, but
  1509. wishes to preserve as much as possible of the ancillary information in
  1510. the file. Examples of PNG editors are a program that adds or modifies
  1511. text chunks, and a program that adds a suggested palette to a 24-bit
  1512. RGB PNG file. Ordinary image editors are not PNG editors in this
  1513. sense, because they usually discard any unrecognized information while
  1514. reading in an image. (Note: we strongly encourage programs handling
  1515. PNG files to preserve ancillary information whenever possible.) 
  1516.  
  1517. As an example of possible problems, consider a hypothetical new
  1518. ancillary chunk type that is safe-to-copy and is required to appear after
  1519. PLTE if PLTE is present (presumably PLTE affects the meaning of the
  1520. chunk in some way). If our program to add a suggested PLTE to a file
  1521. does not recognize this new chunk, it may insert PLTE in the wrong
  1522. place, namely after the new chunk. We could prevent such problems by
  1523. requiring PNG editors to discard any unknown chunks, but that is a very
  1524. unattractive solution. 
  1525.  
  1526. To prevent this type of problem while allowing for future extension, we
  1527. put some constraints on both the behavior of PNG editors and the
  1528. allowed ordering requirements for chunks. The rules for PNG editors
  1529. are: 
  1530.  
  1531.  1. When copying an unknown unsafe-to-copy ancillary chunk, a
  1532.    PNG editor may not move the chunk relative to any critical
  1533.    chunk. It may relocate the chunk freely relative to other
  1534.    ancillary chunks that occur between the same pair of critical
  1535.    chunks. (This is well defined since the editor may not add, delete,
  1536.    or reorder critical chunks if it is preserving unsafe-to-copy
  1537.    chunks.) 
  1538.  2. When copying an unknown safe-to-copy ancillary chunk, a
  1539.    PNG editor may not move the chunk from before IDAT to after 
  1540.    IDAT or vice versa. (This is well defined because IDAT is always
  1541.    present.) Any other reordering is permitted. 
  1542.  3. When copying a known chunk type, an editor need only honor
  1543.    the specific chunk ordering rules that exist for that chunk type.
  1544.    However, it may always choose to apply the above general rules
  1545.    instead. 
  1546.  
  1547. Therefore, the actual ordering rules for any ancillary chunk type cannot
  1548. be any stricter than this: 
  1549.  
  1550.  o Unsafe-to-copy chunks may have ordering requirements
  1551.    relative to critical chunks. 
  1552.  o Safe-to-copy chunks may have ordering requirements relative
  1553.    to IDAT. 
  1554.  
  1555. Note that critical chunks can have arbitrary ordering requirements,
  1556. because PNG editors are required to give up if they encounter unknown
  1557. critical chunks. A PNG editor must always know the ordering rules for
  1558. any critical chunk type that it deals with. For example, IHDR has the
  1559. special ordering rule that it must always appear first. 
  1560.  
  1561. Decoders may not assume more about the positioning of any
  1562. ancillary chunk than is specified by the chunk ordering rules. In
  1563. particular, it is never valid to assume that a specific ancillary chunk type
  1564. occurs with any particular positioning relative to other ancillary chunks.
  1565. (For example, it is unsafe to assume that your private ancillary chunk
  1566. occurs immediately before IEND. Even if your application always writes
  1567. it there, a PNG editor might have inserted some other ancillary chunk
  1568. in between. But you can safely assume that your chunk will remain
  1569. somewhere between IDAT and IEND.) 
  1570.  
  1571. See also Chunk naming conventions. 
  1572.  
  1573. 8. Multi-Image Extension
  1574. ========================
  1575.  
  1576. PNG itself is strictly a single-image format. However, it may be
  1577. necessary to store multiple images within one file; for example, this is
  1578. needed to convert some GIF files. For this purpose, a multi-image
  1579. format will be defined in the near future. PNG decoders will not be
  1580. required to support the multi-image extension. 
  1581.  
  1582. 9. Recommendations for Encoders
  1583. ===============================
  1584.  
  1585. This chapter gives some recommendations for encoder behavior. The
  1586. only absolute requirement on a PNG encoder is that it produce files
  1587. which conform to the format specified in the preceding chapters.
  1588. However, best results will usually be achieved by following these
  1589. recommendations. 
  1590.  
  1591. Bitdepth scaling
  1592. ================
  1593.  
  1594. When scaling input values that have a bit depth that cannot be directly
  1595. represented in PNG, an excellent approximation to the correct value
  1596. can be achieved by shifting the valid bits to begin in the most significant
  1597. bit and repeating the most significant bits into the open bits. 
  1598.  
  1599. For example, if 5 bits per channel are available in the source data,
  1600. conversion to a bitdepth of 8 can be achieved as follows: 
  1601.  
  1602. If the value for a sample in the source data is 27 (in a range from 0-31),
  1603. then the original bits are: 
  1604.  
  1605. 4 3 2 1 0
  1606. ---------
  1607. 1 1 0 1 1
  1608.  
  1609. Converted to a bitdepth of 8, the best value is 222: 
  1610.  
  1611. 7 6 5 4 3  2 1 0
  1612. ----------------
  1613. 1 1 0 1 1  1 1 0
  1614. |=======|  |===|
  1615.     |      Leftmost Bits Repeated to Fill Open Bits
  1616.     |
  1617. Original Bits
  1618.  
  1619. Note that this scaling can be reversed simply by shifting right. 
  1620.  
  1621. Scaling by simply shifting left by three bits is incorrect, since the
  1622. resulting data would have a range less than the desired full range. (For
  1623. 5-bit input data, the maximum output would be 248 = 11111000, which
  1624. is not full brightness.) 
  1625.  
  1626. It is recommended that the sBIT chunk be included when bitdepth
  1627. scaling has been performed, to record the original data depth. 
  1628.  
  1629. Encoder gamma handling
  1630. ======================
  1631.  
  1632. If it is possible for the encoder to determine the image gamma, or to
  1633. make a strong guess based on the hardware on which it runs, then the
  1634. encoder is strongly encouraged to output the gAMA chunk. 
  1635.  
  1636. A linear brightness level, expressed as a floating-point value in the
  1637. range 0 to 1, may be converted to a gamma-corrected pixel value by 
  1638.  
  1639.   gbright := bright ^ gamma
  1640.   pixelval := ROUND(gbright * MAXPIXVAL)
  1641.  
  1642. Computer graphics renderers often do not perform gamma encoding,
  1643. instead making pixel values directly proportional to scene brightness.
  1644. This "linear" pixel encoding is equivalent to gamma encoding with a
  1645. gamma of 1.0, so graphics programs that produce linear pixels should
  1646. always put out a gAMA chunk specifying a gamma of 1.0. 
  1647.  
  1648. If the encoder knows that the image has been displayed satisfactorily on
  1649. a display of gamma display_gamma, then the image can be marked as
  1650. having gamma 1.0/display_gamma. 
  1651.  
  1652. It is not recommended that encoders attempt to convert supplied images
  1653. to a different gamma. Store the data in the file without conversion, and
  1654. record the source gamma. Gamma conversion at encode time is a bad
  1655. idea because gamma adjustment of digital pixel data is inherently lossy,
  1656. due to roundoff error (8 or so bits is not really enough accuracy). Thus
  1657. encode-time conversion permanently degrades the image. Worse, if the
  1658. eventual decoder wants the data with some other gamma, then two
  1659. conversions occur, each introducing roundoff error. Better to store the
  1660. data losslessly and incur at most one conversion when the image is
  1661. finally displayed. 
  1662.  
  1663. Gamma does not apply to alpha channel values; alpha is always
  1664. represented linearly. 
  1665.  
  1666. See Recommendations for Decoders: Decoder gamma handling for
  1667. more details. 
  1668.  
  1669. Alpha channel creation
  1670. ======================
  1671.  
  1672. The alpha channel may be regarded either as a mask that temporarily
  1673. hides transparent parts of the image, or as a means for constructing a
  1674. non-rectangular image. In the first case, the color values of fully
  1675. transparent pixels should be preserved for future use. In the second case,
  1676. the transparent pixels carry no useful data and are simply there to fill
  1677. out the rectangular image area required by PNG. In this case, fully
  1678. transparent pixels should all be assigned the same color value for best
  1679. compression. 
  1680.  
  1681. Encoders should keep in mind the possibility that a viewer will ignore
  1682. transparency control. Hence, the colors assigned to transparent pixels
  1683. should be reasonable background colors whenever feasible. 
  1684.  
  1685. For applications that do not require a full alpha channel, or cannot
  1686. afford the price in compression efficiency, the tRNS transparency
  1687. chunk is also available. 
  1688.  
  1689. If the image has a known background color, this color should be written
  1690. in the bKGD chunk. Even viewers that ignore transparency may use the 
  1691. bKGD color to fill unused screen area. 
  1692.  
  1693. If the original image has premultiplied (also called "associated") alpha
  1694. data, convert it to PNG's non-premultiplied format by dividing each
  1695. RGB value by the corresponding alpha value, then multiplying by the
  1696. maximum value for the image bit depth. In valid premultiplied data, the
  1697. RGB values never exceed their corresponding alpha values, so the result
  1698. of the division should always be in the range 0 to 1. If the alpha value is
  1699. zero, output black (zeroes). 
  1700.  
  1701. Filter selection
  1702. ================
  1703.  
  1704. For images of color type 3 (palette-based color), filter type 0 (none) is
  1705. usually the most effective. 
  1706.  
  1707. Filter type 0 is also recommended for images of bit depths less than 8.
  1708. For low-bit-depth grayscale images, it may be a net win to expand the
  1709. image to 8-bit representation and apply filtering, but this is rare. 
  1710.  
  1711. For truecolor and grayscale images, any of the five filters may prove the
  1712. most effective. If an encoder wishes to use a fixed filter choice, the Paeth
  1713. filter is most likely to be the best. 
  1714.  
  1715. For best compression of truecolor and grayscale images, we recommend
  1716. an adaptive filtering approach in which a filter is chosen for each
  1717. scanline. The following simple heuristic has performed well in early
  1718. tests: compute the output scanline using all five filters, and select the
  1719. filter which gives the smallest sum of absolute values of outputs.
  1720. (Consider the output bytes as signed differences for this test.) This
  1721. method usually outperforms any single fixed filter choice. However, it is
  1722. likely that much better heuristics will be found as more experience is
  1723. gained with PNG. 
  1724.  
  1725. Filtering according to these recommendations is effective on interlaced
  1726. as well as noninterlaced images. 
  1727.  
  1728. Text chunk processing
  1729. =====================
  1730.  
  1731. Note that a nonempty keyword must be provided for each text chunk.
  1732. The generic keyword "Comment" may be used if no better description of
  1733. the text is available. 
  1734.  
  1735. Encoders should discourage the creation of single lines of text longer
  1736. than 79 characters, in order to facilitate easy reading. 
  1737.  
  1738. If an encoder chooses to support output of zTXt compressed text
  1739. chunks, it is recommended that text less than 1K (1024 bytes) in size be
  1740. output using uncompressed tEXt chunks. In particular, it is
  1741. recommended that the basic title and author keywords always be output
  1742. using uncompressed tEXt chunks. Lengthy disclaimers, on the other
  1743. hand, are an ideal candidate for zTXt. 
  1744.  
  1745. Placing large tEXt and zTXt chunks after the image data (after IDAT)
  1746. may speed up image display in some situations, since the decoder won't
  1747. have to read over the text to get to the image data. But it is
  1748. recommended that small text chunks, such as the image title, appear
  1749. before IDAT. 
  1750.  
  1751. Registering proprietary chunks
  1752. ==============================
  1753.  
  1754. If you want others outside your organization to understand a chunk type
  1755. that you invent, contact the maintainers of the PNG specification to
  1756. submit a proposed chunk name and definition for addition to the list of
  1757. special-purpose public chunks (see Additional Chunk Types). 
  1758.  
  1759. New public chunks will be only be registered if they are of use to others
  1760. and do not violate the design philosophy of PNG. Chunk registration is
  1761. not automatic, although it is the intent of the authors that it be
  1762. straightforward when a new chunk of potentially wide application is
  1763. needed. Note that the creation of new critical chunk types is discouraged
  1764. unless absolutely necessary. 
  1765.  
  1766. If you do not desire that others outside your organization understand the
  1767. chunk type, you may use a private chunk name by specifying a lowercase
  1768. letter for the second character. Such chunk types need not be registered.
  1769. But note that others may use the same private chunk name, so it is
  1770. prudent to store additional identifying information at the beginning of
  1771. the chunk data. 
  1772.  
  1773. Please note that if you want to use a private chunk for information that
  1774. is not essential to view the image, and have any desire whatsoever that
  1775. others not using your own viewer software be able to view the image, you
  1776. should use an ancillary chunk type (first character is lowercase) rather
  1777. than a critical chunk type (first character uppercase). 
  1778.  
  1779. If an ancillary chunk is to contain textual information that might be of
  1780. interest to a human user, it is recommended that a special chunk type 
  1781. not be used. Instead use a tEXt chunk and define a suitable keyword. In
  1782. this way, the information will be available to users not using your
  1783. software. 
  1784.  
  1785. If of general usefulness, new keywords for tEXt chunks may be
  1786. registered with the maintainers of the PNG specification. Keywords
  1787. should be chosen to be reasonably self-explanatory, since the idea is to
  1788. let other users figure out what the chunk contains. 
  1789.  
  1790. 10. Recommendations for Decoders
  1791. ================================
  1792.  
  1793. This chapter gives some recommendations for decoder behavior. The
  1794. only absolute requirement on a PNG decoder is that it successfully read
  1795. any file conforming to the format specified in the preceding chapters.
  1796. However, best results will usually be achieved by following these
  1797. recommendations. 
  1798.  
  1799. Chunk error checking
  1800. ====================
  1801.  
  1802. Unknown chunk types must be handled as described under Chunk
  1803. naming conventions. 
  1804.  
  1805. It is strongly recommended that decoders verify the CRC on each chunk.
  1806.  
  1807. For known-length chunks such as IHDR, decoders should treat an
  1808. unexpected chunk length as an error. Future extensions to this
  1809. specification will not add new fields to existing chunks; instead, new
  1810. chunk types will be added to carry any new information. 
  1811.  
  1812. Unexpected values in fields of known chunks (for example, an
  1813. unexpected compression type in the IHDR chunk) should be checked for
  1814. and treated as errors. 
  1815.  
  1816. Pixel dimensions
  1817. ================
  1818.  
  1819. Non-square pixels can be represented (see the pHYs chunk), but
  1820. viewers are not required to account for them; a viewer may present any
  1821. PNG file as though its pixels are square. 
  1822.  
  1823. Conversely, viewers running on display hardware with non-square
  1824. pixels are strongly encouraged to rescale images for proper display. 
  1825.  
  1826. Truecolor image handling
  1827. ========================
  1828.  
  1829. To achieve PNG's goal of universal interchangeability, decoders are
  1830. required to accept all types of PNG image: palette, truecolor, and
  1831. grayscale. Viewers running on palette-mapped display hardware need to
  1832. be able to reduce truecolor images to palette form for viewing. This
  1833. process is usually called "color quantization". 
  1834.  
  1835. A simple, fast way of doing this is to reduce the image to a fixed palette.
  1836. Palettes with uniform color spacing ("color cubes") are usually used to
  1837. minimize the per-pixel computation. For photograph-like images,
  1838. dithering is recommended to avoid ugly contours in what should be
  1839. smooth gradients; however, dithering introduces graininess which may
  1840. be objectionable. 
  1841.  
  1842. The quality of rendering can be improved substantially by using a
  1843. palette chosen specifically for the image, since a color cube usually has
  1844. numerous entries that are unused in any particular image. This
  1845. approach requires more work, first in choosing the palette, and second
  1846. in mapping individual pixels to the closest available color. PNG allows
  1847. the encoder to supply a suggested palette in a PLTE chunk, but not all
  1848. encoders will do so, and the suggested palette may be unsuitable in any
  1849. case (it may have too many or too few colors). High-quality viewers will
  1850. therefore need to have a palette selection routine at hand. A large
  1851. lookup table is usually the most feasible way of mapping individual
  1852. pixels to palette entries with adequate speed. 
  1853.  
  1854. Numerous implementations of color quantization are available. The
  1855. PNG reference implementation will include code for the purpose. 
  1856.  
  1857. Decoder gamma handling
  1858. ======================
  1859.  
  1860. To produce correct tone reproduction, a good image display program
  1861. must take into account the gammas of both the image file and the
  1862. display device. This can be done by calculating 
  1863.  
  1864.   gbright := pixelval / MAXPIXVAL
  1865.   bright := gbright ^ (1.0 / file_gamma)
  1866.   gcvideo := bright ^ (1.0 / display_gamma)
  1867.   fbval := ROUND(gcvideo * MAXFBVAL)
  1868.  
  1869. where MAXPIXVAL is the maximum pixel value in the file (255 for
  1870. 8-bit, 65535 for 16-bit, etc), MAXFBVAL is the maximum value of a
  1871. frame buffer pixel (255 for 8-bit, 31 for 5-bit, etc), pixelval is the
  1872. value of the pixel in the PNG file, and fbval is the value to write into
  1873. the frame buffer. The first line converts from pixel code into a
  1874. normalized 0 to 1 floating point value, the second undoes the encoding
  1875. of the image file to produce a linear brightness value, the third line
  1876. pre-corrects for the monitor's gamma response, and the fourth converts
  1877. to an integer frame buffer pixel. In practice the second and third lines
  1878. can be merged into 
  1879.  
  1880.   gcvideo := gbright ^ (1.0 / (file_gamma * display_gamma))
  1881.  
  1882. so as to perform only one power calculation. For color images, the entire
  1883. calculation is performed separately for R, G, and B values. 
  1884.  
  1885. It is not necessary to perform transcendental math for every pixel!
  1886. Instead, compute a lookup table that gives the correct output value for
  1887. every pixel value. This requires only 256 calculations per image (for
  1888. 8-bit accuracy), not one calculation per pixel. For palette-based
  1889. images, a one-time correction of the palette is sufficient. 
  1890.  
  1891. In some cases even computing a gamma lookup table may be a concern.
  1892. In these cases, viewers are encouraged to have precomputed gamma
  1893. correction tables for file_gamma values of 1.0 and 0.45 and some
  1894. reasonable single display_gamma value, and to use the table closest to
  1895. the gamma indicated in the file. This will produce acceptable results for
  1896. the majority of real files. 
  1897.  
  1898. When the incoming image has unknown gamma (no gAMA chunk),
  1899. choose a likely default file_gamma value, but allow the user to select a
  1900. new one if the result proves too dark or too light. 
  1901.  
  1902. In practice, it is often difficult to determine what value of
  1903. display_gamma should be used. In systems with no built-in gamma
  1904. correction, the display_gamma is determined entirely by the CRT.
  1905. Assuming a value of 2.2 is recommended, unless you have detailed
  1906. calibration measurements of this particular CRT available. 
  1907.  
  1908. However, many modern frame buffers have lookup tables that are used
  1909. to perform gamma correction, and on these systems the display_gamma
  1910. value should be the gamma of the lookup table and CRT combined. You
  1911. may not be able to find out what the lookup table contains from within
  1912. an image viewer application, so you may have to ask the user what the
  1913. system's gamma value is. Unfortunately, different manufacturers use
  1914. different ways of specifying what should go into the lookup table, so
  1915. interpretation of the system gamma value is system-dependent. 
  1916.  
  1917. Here are examples of how to deal with some known systems: 
  1918.  
  1919.  o On many Macintosh systems, there is a "gamma" control panel
  1920.    that lets you select one of a small set of gamma values (1.0, 1.4,
  1921.    1.8, 2.2). These numbers are the combined gamma of the
  1922.    hardware table and the CRT, and so they are exactly the value
  1923.    that the decoder needs to use as display_gamma. With the
  1924.    "gamma" control panel turned off, or not present at all, the
  1925.    default Macintosh system gamma is 1.8. 
  1926.  o On recent SGI systems, there is a hardware gamma-correction
  1927.    table whose contents are controlled by the (privileged) "gamma"
  1928.    program. The gamma of the table is actually the reciprocal of
  1929.    the number that "gamma" prints, and does not include the CRT
  1930.    gamma. To obtain the display_gamma, you need to find the SGI
  1931.    system gamma (either by looking in a file, or asking the user) and
  1932.    then calculating 
  1933.  
  1934.      display_gamma = 2.2 / SGI_system_gamma
  1935.  
  1936.    You will find SGI systems with the system gamma set to 1.0 and
  1937.    2.2 (or higher), but the default when machines are shipped is 1.7. 
  1938.  o On frame buffers that have hardware gamma correction tables,
  1939.    and which are calibrated to display linear pixels correctly,
  1940.    display_gamma is 1.0. 
  1941.  o Many workstations and Xterms and PC displays lack gamma
  1942.    correction hardware. Here, assume that display_gamma is 2.2. 
  1943.  
  1944. We should point out that there is a fudge factor built into the use of the
  1945. magic value "2.2" as the assumed CRT gamma in the calculations
  1946. above. Real CRTs usually have a higher gamma than this, around 2.8 in
  1947. fact. By doing the display gamma correction for a CRT gamma of only
  1948. 2.2, we get an image on screen that is slightly higher in contrast than the
  1949. original scene. This is normal TV and film practice, and we are
  1950. continuing it here. Generally, writers of display programs are best to
  1951. assume that CRT gamma is 2.2 rather than using actual measurements. 
  1952.  
  1953. If you have carefully measured the gamma of your CRT, you might want
  1954. to set display_gamma to your_CRT_gamma/1.25, in order to preserve
  1955. this intentional contrast boost. 
  1956.  
  1957. Finally, note that the response of real displays is actually more complex
  1958. than can be described by a single number (display_gamma). If actual
  1959. measurements of the monitor's light output as a function of voltage
  1960. input are available, the third and fourth lines of the computation above
  1961. may be replaced by a lookup in these measurements, to find the actual
  1962. frame buffer value that most nearly gives the desired brightness. 
  1963.  
  1964. Background color
  1965. ================
  1966.  
  1967. Viewers which have a specific background against which to present the
  1968. image will ignore the bKGD chunk, but viewers with no preset
  1969. background color may choose to honor it. The background color will
  1970. typically be used to fill unused screen space around the image, as well as
  1971. any transparent pixels within the image. (Thus, bKGD is valid and useful
  1972. even when the image does not use transparency.) If no bKGD chunk is
  1973. present, the viewer must make its own decision about a suitable
  1974. background color. 
  1975.  
  1976. Alpha channel processing
  1977. ========================
  1978.  
  1979. In the most general case, the alpha channel can be used to composite a
  1980. foreground image against a background image; the PNG file defines the
  1981. foreground image and the transparency mask, but not the background
  1982. image. Decoders are not required to support this most general case. It is
  1983. expected that most will be able to support compositing against a single
  1984. background color, however. 
  1985.  
  1986. The equation for computing a composited pixel value is 
  1987.  
  1988.   output := alpha * foreground + (1-alpha) * background
  1989.  
  1990. where alpha and the input and output sample values are expressed as
  1991. fractions in the range 0 to 1. This computation should be performed
  1992. with linear (non-gamma-corrected) sample values. For color images,
  1993. the computation is done separately for R, G, and B samples. 
  1994.  
  1995. The following code illustrates the general case of compositing a
  1996. foreground image over a background image. It assumes that you have
  1997. the original pixel data available for the background image, and that
  1998. output is to a frame buffer for display. Other variants are possible; see
  1999. the comments below the code. The code allows the bit depths and
  2000. gamma values of foreground image, background image, and frame
  2001. buffer/CRT to all be different. Don't assume they are the same without
  2002. checking! 
  2003.  
  2004. There are line numbers for referencing code in the comments below.
  2005. Other than that, this is standard C. 
  2006.  
  2007. 01  int foreground[4];      /* file pixel: R, G, B, A */
  2008. 02  int background[3];      /* file background color: R, G, B */
  2009. 03  int fbpix[3];           /* frame buffer pixel */
  2010. 04  int fg_maxpixval;       /* foreground max pixel */
  2011. 05  int bg_maxpixval;       /* background max pixel */
  2012. 06  int fb_maxpixval;       /* frame buffer max pixel */
  2013. 07  int ialpha;
  2014. 08  float alpha, compalpha;
  2015. 09  float gamfg, linfg, gambg, linbg, comppix, gcvideo;
  2016.  
  2017.     /* Get max pixel value in files and frame buffer */
  2018. 10  fg_maxpixval = (1 << fg_bit_depth) - 1;
  2019. 11  bg_maxpixval = (1 << bg_bit_depth) - 1;
  2020. 12  fb_maxpixval = (1 << frame_buffer_bit_depth) - 1;
  2021.     /*
  2022.      * Get integer version of alpha.
  2023.      * Check for opaque and transparent special cases;
  2024.      * no compositing needed if so.
  2025.      *
  2026.      * We show the whole gamma decode/correct process in
  2027.      * floating point, but it would more likely be done
  2028.      * with lookup tables.
  2029.      */
  2030. 13  ialpha = foreground[3];
  2031. 14  if (ialpha == 0) {
  2032.         /*
  2033.          * Foreground image is transparent here.
  2034.          * If the background image is already in the frame
  2035.          * buffer, there is nothing to do.
  2036.          */
  2037. 15      ;
  2038. 16  } else if (ialpha == fg_maxpixval) {
  2039. 17      for (i = 0; i < 3; i++ {
  2040. 18          gamfg = (float) foreground[i] / fg_maxpixval;
  2041. 19          linfg = pow(gamfg, 1.0/fg_gamma);
  2042. 20          comppix = linfg;
  2043. 21          gcvideo = pow(comppix, 1.0/display_gamma);
  2044. 22          fbpix[i] = (int) (gcvideo * fb_maxpixval + 0.5);
  2045. 23      }
  2046. 24  } else {
  2047.         /*
  2048.          * Compositing is necessary.
  2049.          * Get floating-point alpha and its complement.
  2050.          * Note: alpha is always linear; gamma does not
  2051.          * affect it.
  2052.          */
  2053. 25      alpha = (float) ialpha / fg_maxpixval;
  2054. 26      compalpha = 1.0 - alpha;
  2055.  
  2056. 27      for (i = 0; i < 3; i++ {
  2057.             /*
  2058.              * Convert foreground and background to floating point,
  2059.              * then linearize (undo gamma encoding).
  2060.              */
  2061. 28          gamfg = (float) foreground[i] / fg_maxpixval;
  2062. 29          linfg = pow(gamfg, 1.0/fg_gamma);
  2063. 30          gambg = (float) background[i] / bg_maxpixval;
  2064. 31          linbg = pow(gambg, 1.0/bg_gamma);
  2065.             /*
  2066.              * Composite.
  2067.              */
  2068. 32          comppix = linfg * alpha + linbg * compalpha;
  2069.             /*
  2070.              * Gamma correct for display.
  2071.              * Convert to integer frame buffer pixel.
  2072.              */
  2073. 33          gcvideo = pow(comppix, 1.0/display_gamma);
  2074. 34          fbpix[i] = (int) (gcvideo * fb_maxpixval + 0.5);
  2075. 35      }
  2076. 36  }
  2077.  
  2078. Variations: 
  2079.  
  2080.  1. If output is to another PNG image file instead of a frame buffer,
  2081.    lines 21, 22, 33, and 34 should be changed to be something like: 
  2082.  
  2083.            /*
  2084.             * Gamma encode for storage in output file.
  2085.             * Convert to integer pixel value.
  2086.             */
  2087.            gamout = pow(comppix, outfile_gamma);
  2088.            outpix[i] = (int) (gamout * out_maxpixval + 0.5);
  2089.  
  2090.    Also, it becomes necessary to process background pixels when
  2091.    alpha is zero, rather than just skipping pixels. Thus, line 15 must
  2092.    be replaced by copies of lines 18-22, but processing background
  2093.    instead of foreground pixel values. 
  2094.  2. If the bit depth of the output file, foreground file, and
  2095.    background file are all the same, and the three gamma values
  2096.    also match, then the no-compositing code in lines 14-23 reduces
  2097.    to nothing more than copying pixel values from the input file to
  2098.    the output file if alpha is one, or copying pixel values from
  2099.    background to output file if alpha is zero. Since alpha is typically
  2100.    either zero or one for the vast majority of pixels in an image, this
  2101.    is a great savings. No gamma computations are needed for most
  2102.    pixels. 
  2103.  3. When the bit depths and gamma values all match, it may appear
  2104.    attractive to skip the gamma decorrection and correction (lines
  2105.    28-31, 33-34) and just perform line 32 using gamma-encoded
  2106.    sample values. Although this doesn't hurt image quality too
  2107.    badly, the time savings are small if alpha values of zero and one
  2108.    are special-cased as recommended here. 
  2109.  4. If the original pixel values of the background image are no
  2110.    longer available, only processed frame buffer pixels left by
  2111.    display of the background image, then lines 30 and 31 must
  2112.    extract intensity from the frame buffer pixel values using code
  2113.    like: 
  2114.  
  2115.            /*
  2116.             * Decode frame buffer value back into linear space.
  2117.             */
  2118.            gcvideo = (float) (fbpix[i] / fb_maxpixval);
  2119.            linbg = pow(gcvideo, display_gamma);
  2120.  
  2121.    However, some roundoff error can result, so it is better to have
  2122.    the original background pixels available if at all possible. 
  2123.  5. Note that lines 18-22 are performing exactly the same gamma
  2124.    computation that is done when no alpha channel is present. So,
  2125.    if you handle the no-alpha case with a lookup table, you can use
  2126.    the same lookup table here. Lines 28-31 and 33-34 can also be
  2127.    done with lookup tables. 
  2128.  6. Of course, everything here can be done in integer arithmetic.
  2129.    Just be careful to maintain sufficient precision all the way
  2130.    through. 
  2131.  
  2132. Note: in floating point, no overflow or underflow checks are needed,
  2133. because the input pixel values are guaranteed to be between 0 and 1, and
  2134. compositing always yields a result that is in between the input values
  2135. (inclusive). With integer arithmetic, some roundoff-error analysis
  2136. might be needed to guarantee no overflow or underflow. 
  2137.  
  2138. When displaying a PNG image with full alpha channel, it is important
  2139. to be able to composite the image against some background, even if it's
  2140. only black. Ignoring the alpha channel will cause PNG images that have
  2141. been converted from an associated-alpha representation to look wrong.
  2142. (Of course, if the alpha channel is a separate transparency mask, then
  2143. ignoring alpha is a useful option: it allows the hidden parts of the image
  2144. to be recovered.) 
  2145.  
  2146. When dealing with PNG images that have a tRNS chunk, it is
  2147. reasonable to assume that the transparency information is a mask
  2148. rather than associated-alpha coverage data. In this case, it is an
  2149. acceptable shortcut to interpret all nonzero alpha values as fully opaque
  2150. (no background). This approach is simple to implement: transparent
  2151. pixels are replaced by the background color, others are unchanged. A
  2152. viewer with no particular background color preference may even choose
  2153. to ignore the tRNS chunk; but if a bKGD chunk is provided, it is better
  2154. to use the specified background color. 
  2155.  
  2156. Progressive display
  2157. ===================
  2158.  
  2159. When receiving images over slow transmission links, decoders can
  2160. improve perceived performance by displaying interlaced images
  2161. progressively. This means that as each pass is received, an
  2162. approximation to the complete image is displayed based on the data
  2163. received so far. One simple yet pleasing effect can be obtained by
  2164. expanding each received pixel to fill a rectangle covering the
  2165. yet-to-be-transmitted pixel positions below and to the right of the
  2166. received pixel. This process can be described by the following
  2167. pseudocode: 
  2168.  
  2169. Starting_Row [1..7] =  { 0, 0, 4, 0, 2, 0, 1 }
  2170. Starting_Col [1..7] =  { 0, 4, 0, 2, 0, 1, 0 }
  2171. Row_Increment [1..7] = { 8, 8, 8, 4, 4, 2, 2 }
  2172. Col_Increment [1..7] = { 8, 8, 4, 4, 2, 2, 1 }
  2173. Block_Height [1..7] =  { 8, 8, 4, 4, 2, 2, 1 }
  2174. Block_Width [1..7] =   { 8, 4, 4, 2, 2, 1, 1 }
  2175.  
  2176. pass := 1
  2177. while pass <= 7
  2178. begin
  2179.     row := Starting_Row[pass]
  2180.  
  2181.     while row < height
  2182.     begin
  2183.         col := Starting_Col[pass]
  2184.  
  2185.         while col < width
  2186.         begin
  2187.             visit (row, col,
  2188.                    min (Block_Height[pass], height - row),
  2189.                    min (Block_Width[pass], width - col))
  2190.             col := col + Col_Increment[pass]
  2191.         end
  2192.         row := row + Row_Increment[pass]
  2193.     end
  2194.  
  2195.     pass := pass + 1
  2196. end
  2197.  
  2198. Here, the function "visit(row,column,height,width)" obtains the next
  2199. transmitted pixel and paints a rectangle of the specified height and
  2200. width, whose upper-left corner is at the specified row and column, using
  2201. the color indicated by the pixel. Note that row and column are measured
  2202. from 0,0 at the upper left corner. 
  2203.  
  2204. If the decoder is merging the received image with a background image, it
  2205. may be more convenient just to paint the received pixel positions; that
  2206. is, the "visit()" function sets only the pixel at the specified row and
  2207. column, not the whole rectangle. This produces a "fade-in" effect as the
  2208. new image gradually replaces the old. An advantage of this approach is
  2209. that proper alpha or transparency processing can be done as each pixel
  2210. is replaced. Painting a rectangle as described above will overwrite
  2211. background-image pixels that may be needed later, if the pixels
  2212. eventually received for those positions turn out to be wholly or partially
  2213. transparent. Of course, this is only a problem if the background image is
  2214. not stored anywhere offscreen. 
  2215.  
  2216. Palette histogram usage
  2217. =======================
  2218.  
  2219. If the viewer is only short a few colors, it is usually adequate to drop the
  2220. least-used colors from the palette. To reduce the number of colors
  2221. substantially, it's best to choose entirely new representative colors,
  2222. rather than trying to use a subset of the existing palette. This amounts to
  2223. performing a new color quantization step; however, the existing palette
  2224. and histogram can be used as the input data, thus avoiding a scan of the
  2225. image data. 
  2226.  
  2227. If no histogram chunk is provided, a decoder can of course develop its
  2228. own, at the cost of an extra pass over the image data. 
  2229.  
  2230. Text chunk processing
  2231. =====================
  2232.  
  2233. If practical, decoders should have a way to display to the user all tEXt
  2234. and zTXt chunks found in the file. Even if the decoder does not
  2235. recognize a particular text keyword, the user may well be able to
  2236. understand it. 
  2237.  
  2238. Decoders should be prepared to display text chunks which contain any
  2239. number of printing characters between newline characters, even though
  2240. encoders are encouraged to avoid creating lines in excess of 79
  2241. characters. 
  2242.  
  2243. 11. Appendix: Rationale
  2244. =======================
  2245.  
  2246. (This appendix is not part of the formal PNG specification.) 
  2247.  
  2248. This appendix gives the reasoning behind some of the design decisions in
  2249. PNG. Many of these decisions were the subject of considerable debate.
  2250. The authors freely admit that another group might have made different
  2251. decisions; however, we believe that our choices are defensible and
  2252. consistent. 
  2253.  
  2254. Why a new file format?
  2255. ======================
  2256.  
  2257. Does the world really need yet another graphics format? We believe so.
  2258. GIF is no longer freely usable, but no other commonly used format can
  2259. directly replace it, as is discussed in more detail below. We might have
  2260. used an adaptation of an existing format, for example GIF with an
  2261. unpatented compression scheme. But this would require new code
  2262. anyway; it would not be all that much easier to implement than a whole
  2263. new file format. (PNG is designed to be simple to implement, with the
  2264. exception of the compression engine, which would be needed in any
  2265. case.) We feel that this is an excellent opportunity to design a new
  2266. format that fixes some of the known limitations of GIF. 
  2267.  
  2268. Why these features?
  2269. ===================
  2270.  
  2271. The features chosen for PNG are intended to address the needs of
  2272. applications that previously used the special strengths of GIF. In
  2273. particular, GIF is well adapted for on-line communications because of
  2274. its streamability and progressive display capability. PNG shares those
  2275. attributes. 
  2276.  
  2277. We have also addressed some of the widely known shortcomings of GIF.
  2278. In particular, PNG supports truecolor images. We know of no widely
  2279. used image format that losslessly compresses truecolor images as
  2280. effectively as PNG does. We hope that PNG will make use of truecolor
  2281. images more practical and widespread. 
  2282.  
  2283. Some form of transparency control is desirable for applications in which
  2284. images are displayed against a background or together with other
  2285. images. GIF provided a simple transparent-color specification for this
  2286. purpose. PNG supports a full alpha channel as well as transparent-color
  2287. specifications. This allows both highly flexible transparency and
  2288. compression efficiency. 
  2289.  
  2290. Robustness against transmission errors has been an important
  2291. consideration. For example, images transferred across Internet are often
  2292. mistakenly processed as text, leading to file corruption. PNG is designed
  2293. so that such errors can be detected quickly and reliably. 
  2294.  
  2295. PNG has been expressly designed not to be completely dependent on a
  2296. single compression technique. Although inflate/deflate compression is
  2297. mentioned in this document, PNG would still exist without it. 
  2298.  
  2299. Why not these features?
  2300. =======================
  2301.  
  2302. Some features have been deliberately omitted from PNG. These choices
  2303. were made to simplify implementation of PNG, promote portability and
  2304. interchangeability, and make the format as simple and foolproof as
  2305. possible for users. In particular: 
  2306.  
  2307.  o There is no uncompressed variant of PNG. It is possible to store
  2308.    uncompressed data by using only uncompressed deflate blocks (a
  2309.    feature normally used to guarantee that deflate does not make
  2310.    incompressible data much larger). However, any software that
  2311.    does not support full deflate/inflate will not be considered
  2312.    compliant with the PNG standard. The two most important
  2313.    features of PNG---portability and compression---are absolute
  2314.    requirements for online applications, and users demand them.
  2315.    Failure to support full deflate/inflate compromises both of these
  2316.    objectives. 
  2317.  o There is no lossy compression in PNG. Existing formats such as
  2318.    JFIF already handle lossy compression well. Furthermore,
  2319.    available lossy compression methods (e.g., JPEG) are far from
  2320.    foolproof to use --- a poor choice of quality level can ruin an
  2321.    image. To avoid user confusion and unintentional loss of
  2322.    information, we feel it is best to keep lossy and lossless formats
  2323.    strictly separate. Also, lossy compression is complex to
  2324.    implement. Adding JPEG support to a PNG decoder might
  2325.    increase its size by an order of magnitude. This would certainly
  2326.    cause some decoders to omit support for the feature, which would
  2327.    destroy our goal of interchangeability. 
  2328.  o There is no support for CMYK or other unusual color spaces.
  2329.    Again, this is in the name of promoting portability. CMYK, in
  2330.    particular, is far too device-dependent to be useful as a portable
  2331.    image representation. 
  2332.  o There is no standard chunk for thumbnail views of images. In
  2333.    discussions with software vendors who use thumbnails in their
  2334.    products, it has become clear that most would not use a
  2335.    "standard" thumbnail chunk. This is partly because every vendor
  2336.    has a distinct idea of what the dimensions and characteristics of
  2337.    a thumbnail should be, and partly because vendors who keep
  2338.    thumbnails in separate files to accommodate varied image
  2339.    formats are not going to stop doing that simply because of a
  2340.    thumbnail chunk in one new format. Proprietary chunks
  2341.    containing vendor-specific thumbnails appear to be more
  2342.    practical than a common thumbnail format. 
  2343.  
  2344. It is worth noting that private extensions to PNG could easily add these
  2345. features. We will not, however, include them as part of the basic PNG
  2346. standard. 
  2347.  
  2348. Basic PNG also does not support multiple images in one file. This
  2349. restriction is a reflection of the reality that many applications do not
  2350. need and will not support multiple images per file. (While the GIF
  2351. standard nominally allows multiple images per file, few applications
  2352. actually support it.) In any case, single images are a fundamentally
  2353. different sort of object from sequences of images. Rather than make
  2354. false promises of interchangeability, we have drawn a clear distinction
  2355. between single-image and multi-image formats. PNG is a single-image
  2356. format. 
  2357.  
  2358. Why not use format XYZ?
  2359. =======================
  2360.  
  2361. Numerous existing formats were considered before deciding to develop
  2362. PNG. None could meet the requirements we felt were important for
  2363. PNG. 
  2364.  
  2365. GIF is no longer suitable as a universal standard because of legal
  2366. entanglements. Although just replacing GIF's compression method
  2367. would avoid that problem, GIF does not support truecolor images, alpha
  2368. channels, or gamma correction. The spec has more subtle problems too.
  2369. Only a small subset of the GIF89 spec is actually portable across a
  2370. variety of implementations, but there is no codification of the most
  2371. portable part of the spec. 
  2372.  
  2373. TIFF is far too complex to meet our goals of simplicity and
  2374. interchangeability. Defining a TIFF subset would meet that objection,
  2375. but would frustrate users making the reasonable assumption that a file
  2376. saved as TIFF from Software XYZ would load into a program
  2377. supporting our flavor of TIFF. Furthermore, TIFF is not designed for
  2378. stream processing, has no provision for progressive display, and does not
  2379. currently provide any good, legally unencumbered, lossless compression
  2380. method. 
  2381.  
  2382. IFF has also been suggested, but is not suitable in detail: available image
  2383. representations are too machine-specific or not adequately compressed.
  2384. The overall chunk structure of IFF is a useful concept which PNG has
  2385. liberally borrowed from, but we did not attempt to be bit-for-bit
  2386. compatible with IFF chunk structure. Again this is due to detailed issues,
  2387. notably the fact that IFF FORMs are not designed to be serially
  2388. writable. 
  2389.  
  2390. Lossless JPEG is not suitable because it does not provide for the storage
  2391. of palette-color images. Furthermore, its lossless truecolor compression
  2392. is often inferior to that of PNG. 
  2393.  
  2394. Byte order
  2395. ==========
  2396.  
  2397. It has been asked why PNG uses network byte order. We have selected
  2398. one byte ordering and used it consistently. Which order in particular is
  2399. of little relevance, but network byte order has the advantage that
  2400. routines to convert to and from it are already available on any platform
  2401. that supports TCP/IP networking, including all PC platforms. The
  2402. functions are trivial and will be included in the reference
  2403. implementation. 
  2404.  
  2405. Interlacing
  2406. ===========
  2407.  
  2408. PNG's two-dimensional interlacing scheme is more complex to
  2409. implement than GIF's line-wise interlacing. It also costs a little more in
  2410. file size. However, it yields an initial image eight times faster than GIF
  2411. (the first pass transmits only 1/64th of the pixels, compared to 1/8th for
  2412. GIF). Although this initial image is coarse, it is useful in many
  2413. situations. For example, if the image is a World Wide Web imagemap
  2414. that the user has seen before, PNG's first pass is enough to determine
  2415. where to click. The PNG scheme also looks better than GIF's, because
  2416. horizontal and vertical resolution never differ by more than a factor of
  2417. two; this avoids the odd "stretched" look seen when interlaced GIFs are
  2418. filled in by replicating scanlines. 
  2419.  
  2420. Why gamma encoding?
  2421. ===================
  2422.  
  2423. Although gamma 1.0 (linear brightness response) might seem a natural
  2424. standard, it is common for images to have a gamma of less than 1.
  2425. There are two good reasons for this: 
  2426.  
  2427.  o CRT hardware typically has a gamma between 2 and 3. Hence,
  2428.    "gamma correction" is a standard part of all video signals. The
  2429.    transmitted image usually has a gamma of 0.45 (NTSC) or 0.36
  2430.    (PAL/SECAM), so images obtained by frame-grabbing video
  2431.    already have this value of gamma. 
  2432.  o An image gamma less than 1 allocates more of the available
  2433.    pixel codes or voltage range to darker areas of the image. This
  2434.    allows photographic-quality images to be stored in only 24
  2435.    bits/pixel without banding artifacts in the darker areas (in most
  2436.    cases). This makes "gamma encoding" a much better way of
  2437.    storing digital images than the simpler linear encoding. 
  2438.  
  2439. In practice, image gamma values around 1.0 and around 0.45 are both
  2440. widely found. Older image standards such as GIF often do not account
  2441. for this fact, leading to widespread problems with images coming out
  2442. "too dark" or "too light". 
  2443.  
  2444. PNG expects viewers to compensate for image gamma at the time that
  2445. the image is displayed. Another possible approach is to expect encoders
  2446. to convert all images to a uniform gamma at encoding time. While that
  2447. method would speed viewers slightly, it has fundamental flaws: 
  2448.  
  2449.  o Gamma correction is inherently lossy due to roundoff error.
  2450.    Requiring conversion at encoding time thus causes irreversible
  2451.    loss. Since PNG is intended to be a lossless storage format, this is
  2452.    undesirable; we should store unmodified source data. 
  2453.  o The encoder might not know the image gamma. If the decoder
  2454.    does gamma correction at viewing time, it can adjust the gamma
  2455.    (correct the displayed brightness) in response to feedback from a
  2456.    human user. The encoder has no such option. 
  2457.  o Whatever "standard" gamma we settled on would be wrong for
  2458.    some displays. Hence viewers would still need gamma correction
  2459.    capability. 
  2460.  
  2461. Since there will always be images with no gamma or an incorrect
  2462. recorded gamma, good viewers will need to incorporate gamma
  2463. correction logic anyway. Gamma correction at viewing time is thus the
  2464. right way to go. 
  2465.  
  2466. Non-premultiplied alpha
  2467. =======================
  2468.  
  2469. PNG uses "unassociated" or "non-premultiplied" alpha so that images
  2470. with separate transparency masks can be stored losslessly. Another
  2471. common technique, "premultiplied alpha", stores pixel values
  2472. premultiplied by the alpha fraction; in effect, the image is already
  2473. composited against a black background. Any image data hidden by the
  2474. transparency mask is irretrievably lost by that method, since multiplying
  2475. by a zero alpha value always produces zero. 
  2476.  
  2477. Some image rendering techniques generate images with premultiplied
  2478. alpha (the alpha value actually represents how much of the pixel is
  2479. covered by the image). This representation can be converted to PNG by
  2480. dividing the RGB values by alpha, except where alpha is zero. The result
  2481. will look good if displayed by a viewer that handles alpha properly, but
  2482. will not look very good if the viewer ignores the alpha channel. 
  2483.  
  2484. Although each form of alpha storage has its advantages, we did not
  2485. want to require all PNG viewers to handle both forms. We standardized
  2486. on non-premultiplied alpha as being the more general case. 
  2487.  
  2488. Filtering
  2489. =========
  2490.  
  2491. PNG includes filtering capability because filtering can significantly
  2492. reduce the compressed size of truecolor and grayscale images. Filtering
  2493. is also sometimes of value on palette images, although this is less
  2494. common. 
  2495.  
  2496. The filter algorithms are defined to operate on bytes, rather than pixels;
  2497. this gains simplicity and speed with very little cost in compression
  2498. performance. Tests have shown that filtering is usually ineffective for
  2499. images with fewer than 8 bits per pixel, so providing pixelwise filtering
  2500. for such images would be pointless. For 16 bit/pixel data, bytewise
  2501. filtering is nearly as effective as pixelwise filtering, because MSBs are
  2502. predicted from adjacent MSBs, and LSBs are predicted from adjacent
  2503. LSBs. 
  2504.  
  2505. The encoder is allowed to change filters for each new scanline. This
  2506. creates no additional complexity for decoders, since a decoder is
  2507. required to contain unfiltering logic for every filter type anyway. The
  2508. only cost is an extra byte per scanline in the pre-compression data
  2509. stream. Our tests showed that when the same filter is selected for all
  2510. scanlines, this extra byte compresses away to almost nothing, so there is
  2511. little storage cost compared to a fixed filter specified for the whole
  2512. image. And the potential benefits of adaptive filtering are too great to
  2513. ignore. Even with the simplistic filter-choice heuristics so far
  2514. discovered, adaptive filtering usually outperforms fixed filters. In
  2515. particular, an adaptive filter can change behavior for successive passes
  2516. of an interlaced image; a fixed filter cannot. 
  2517.  
  2518. The basic filters offered by PNG have been chosen on both theoretical
  2519. and experimental grounds. In particular, it is worth noting that all the
  2520. filters (except "none" and "average") operate by encoding the
  2521. difference between a pixel and one of its neighboring pixels. This is
  2522. usually superior to conventional linear prediction equations because the
  2523. prediction is certain to be one of the possible pixel values. When the
  2524. source data is not full depth (such as 5-bit data scaled up to 8-bit
  2525. depth), this restriction ensures that the number of prediction delta
  2526. values is no more than the number of distinct pixel values present in the
  2527. source data. A linear equation can produce intermediate values not
  2528. actually present in the source data, and thus reduce compression
  2529. efficiency. 
  2530.  
  2531. Text strings
  2532. ============
  2533.  
  2534. Most graphics file formats include the ability to store some textual
  2535. information along with the image. But many applications need more
  2536. than that: they want to be able to store several identifiable pieces of text.
  2537. For example, a database using PNG files to store medical X-rays would
  2538. likely want to include patient's name, doctor's name, etc. A simple way
  2539. to do this in PNG would be to invent new proprietary chunks holding
  2540. text. The disadvantage of such an approach is that other applications
  2541. would have no idea what was in those chunks, and would simply ignore
  2542. them. Instead, we recommend that text information be stored in
  2543. standard tEXt chunks with suitable keywords. Use of tEXt tells any
  2544. PNG viewer that the chunk contains text that may be of interest to a
  2545. human user. Thus, a person looking at the file with another viewer will
  2546. still be able to see the text, and even understand what it is if the
  2547. keywords are reasonably self-explanatory. (To this end, we recommend
  2548. spelled-out keywords, not abbreviations that will be hard for a person to
  2549. understand. Saving a few bytes on a keyword is false economy.) 
  2550.  
  2551. The ISO 8859-1 (Latin-1) character set was chosen as a compromise
  2552. between functionality and portability. Some platforms cannot display
  2553. anything more than 7-bit ASCII characters, while others can handle
  2554. characters beyond the Latin-1 set. We felt that Latin-1 represents a
  2555. widely useful and reasonably portable character set. Latin-1 is a direct
  2556. subset of character sets commonly used on popular platforms such as
  2557. Microsoft Windows and X Windows. It can also be handled on
  2558. Macintosh systems with a simple remapping of characters. 
  2559.  
  2560. There is at present no provision for text employing character sets other
  2561. than the Latin-1 character set. It is recognized that the need for other
  2562. character sets will increase. However, PNG already requires that
  2563. programmers implement a number of new and unfamiliar features, and
  2564. text representation is not PNG's primary purpose. Since PNG provides
  2565. for the creation and public registration of new ancillary chunks of
  2566. general interest, it is expected that text chunks for other character sets,
  2567. such as Unicode, eventually will be registered and increase gradually in
  2568. popularity. 
  2569.  
  2570. PNG file signature
  2571. ==================
  2572.  
  2573. The first eight bytes of a PNG file always contain the following values: 
  2574.  
  2575. (decimal)              137  80  78  71  13  10  26  10
  2576. (hex)                   89  50  4e  47  0d  0a  1a  0a
  2577. (ASCII C notation)    \211   P   N   G  \r  \n \032 \n
  2578.  
  2579. This signature both identifies the file as a PNG file and provides for
  2580. immediate detection of common file-transfer problems. The first two
  2581. bytes distinguish PNG files on systems that expect the first two bytes to
  2582. identify the file type uniquely. The first byte is chosen as a non-ASCII
  2583. value to reduce the probability that a text file may be misrecognized as a
  2584. PNG file; also, it catches bad file transfers that clear bit 7. Bytes two
  2585. through four name the format. The CR-LF sequence catches bad file
  2586. transfers that alter newline sequences. The control-Z character stops
  2587. file display under MS-DOS. The final line feed checks for the inverse of
  2588. the CR-LF translation problem. 
  2589.  
  2590. Additional confidence in correct file transfer can be had by checking
  2591. that the next eight bytes are an IHDR chunk header with the correct
  2592. chunk length. 
  2593.  
  2594. Note that there is no version number in the signature, nor indeed
  2595. anywhere in the file. This is intentional: the chunk mechanism provides
  2596. a better, more flexible way to handle format extensions, as is described
  2597. below. 
  2598.  
  2599. Chunk layout
  2600. ============
  2601.  
  2602. The chunk design allows decoders to skip unrecognized or uninteresting
  2603. chunks: it is simply necessary to skip the appropriate number of bytes, as
  2604. determined from the length field. 
  2605.  
  2606. Limiting chunk length to (2^31)-1 bytes avoids possible problems for
  2607. implementations that cannot conveniently handle 4-byte unsigned
  2608. values. In practice, chunks will usually be much shorter than that
  2609. anyway. 
  2610.  
  2611. A separate CRC is provided for each chunk in order to detect
  2612. badly-transferred images as quickly as possible. In particular, critical
  2613. data such as the image dimensions can be validated before being used.
  2614. The chunk length is excluded in order to permit CRC calculation while
  2615. data is generated (possibly before the length is known, in the case of
  2616. variable-length chunks); this may avoid an extra pass over the data.
  2617. Excluding the length from the CRC does not create any extra risk of
  2618. failing to discover file corruption, since if the length is wrong, the CRC
  2619. check will fail (the CRC will be computed on the wrong bytes and then
  2620. tested against the wrong value from the file). 
  2621.  
  2622. Chunk naming conventions
  2623. ========================
  2624.  
  2625. The chunk naming conventions allow safe, flexible extension of the
  2626. PNG format. This mechanism is much better than a format version
  2627. number, because it works on a feature-by-feature basis rather than
  2628. being an overall indicator. Decoders can process newer files if and only
  2629. if the files use no unknown critical features (as indicated by finding
  2630. unknown critical chunks). Unknown ancillary chunks can be safely
  2631. ignored. Experience has shown that format version numbers hurt
  2632. portability as much as they help. Version numbers tend to be set
  2633. unnecessarily high, leading to older decoders rejecting files that they
  2634. could have processed (this was a serious problem for several years after
  2635. the GIF89 spec came out, for example). Furthermore, private
  2636. extensions can be made either critical or ancillary, and standard
  2637. decoders will react appropriately; overall version numbers are no help
  2638. for private extensions. 
  2639.  
  2640. A hypothetical chunk for vector graphics would be a critical chunk,
  2641. since if ignored, important parts of the intended image would be missing.
  2642. A chunk carrying the Mandelbrot set coordinates for a fractal image
  2643. would be ancillary, since other applications could display the image
  2644. without understanding what it was. In general, a chunk type should be
  2645. made critical only if it is impossible to display a reasonable
  2646. representation of the intended image without interpreting that chunk. 
  2647.  
  2648. The public/private property bit ensures that any newly defined public
  2649. chunk type name cannot conflict with proprietary chunks that may be
  2650. in use somewhere. However, this does not protect users of private chunk
  2651. names from the possibility that someone else may re-use the same
  2652. chunk name for a different purpose. It is a good idea to put additional
  2653. identifying information at the start of the data for any private chunk
  2654. type. 
  2655.  
  2656. When a PNG file is modified, certain ancillary chunks may need to be
  2657. changed to reflect changes in other chunks. For example, a histogram
  2658. chunk needs to be changed if the image data changes. If the encoder
  2659. does not recognize histogram chunks, copying them blindly to a new
  2660. output file is incorrect; such chunks should be dropped. The safe/unsafe
  2661. property bit allows ancillary chunks to be marked appropriately. 
  2662.  
  2663. Not all possible modification scenarios are covered by the safe/unsafe
  2664. semantics. In particular, chunks that are dependent on the total file
  2665. contents are not supported. (An example of such a chunk is an index of 
  2666. IDAT chunk locations within the file: adding a comment chunk would
  2667. inadvertently break the index.) Definition of such chunks is discouraged.
  2668. If absolutely necessary for a particular application, such chunks may be
  2669. made critical chunks, with consequent loss of portability to other
  2670. applications. In general, ancillary chunks may depend on critical chunks
  2671. but not on other ancillary chunks. It is expected that mutually
  2672. dependent information should be put into a single chunk. 
  2673.  
  2674. In some situations it may be unavoidable to make one ancillary chunk
  2675. dependent on another. Although the chunk property bits do not allow
  2676. this case to be represented, a simple solution is available: in the
  2677. dependent chunk, record the CRC of the chunk depended on. It can then
  2678. be determined whether that chunk has been changed by some other
  2679. program. 
  2680.  
  2681. The same technique may be useful for other purposes. For example, if a
  2682. program relies on the palette being in a particular order, it may store a
  2683. private chunk containing the CRC of the PLTE chunk. If this value
  2684. matches when the file is again read in, then it provides high confidence
  2685. that the palette has not been tampered with. Note that it is not
  2686. necessary to mark the private chunk unsafe-to-copy when this
  2687. technique is used; thus, such a private chunk can survive other editing of
  2688. the file. 
  2689.  
  2690. Palette histograms
  2691. ==================
  2692.  
  2693. A viewer may not be able to provide as many colors as are listed in the
  2694. image's palette. (For example, some colors may be reserved by a window
  2695. system.) To produce the best results in this situation, it is helpful to have
  2696. information on the frequency with which each palette index actually
  2697. appears, in order to choose the best palette for dithering or drop the
  2698. least-used colors. Since images are often created once and viewed many
  2699. times, it makes sense to calculate this information in the encoder,
  2700. although it is not mandatory for the encoder to provide it. 
  2701.  
  2702. The same rationale holds good for palettes which are suggested
  2703. quantizations of truecolor images. In this situation, it is recommended
  2704. that the histogram values represent "nearest neighbor" counts, that is,
  2705. the approximate usage of each palette entry if no dithering is applied.
  2706. (These counts will often be available for free as a consequence of
  2707. developing the suggested palette.) 
  2708.  
  2709. Other image formats have usually addressed this problem by specifying
  2710. that the palette entries should appear in order of frequency of use. That
  2711. is an inferior solution, because it doesn't give the viewer nearly as much
  2712. information: the viewer can't determine how much damage will be done
  2713. by dropping the last few colors. Nor does a sorted palette give enough
  2714. information to choose a target palette for dithering, in the case that the
  2715. viewer must reduce the number of colors substantially. A palette
  2716. histogram provides the information needed to choose such a target
  2717. palette without making a pass over the image data. 
  2718.  
  2719. 12. Appendix: Sample CRC Code
  2720. =============================
  2721.  
  2722. The following sample code represents a practical implementation of the
  2723. CRC (Cyclic Redundancy Check) employed in PNG chunks. 
  2724.  
  2725. The sample code provided is in the C programming language. (See also
  2726. ISO 3309 and ITU-T V.42 for a formal specification.) 
  2727.  
  2728. /* table of crc's of all 8-bit messages */
  2729. unsigned long crc_table[256];
  2730.  
  2731. /* Flag: has the table been computed? Initially false. */
  2732. int crc_table_computed = 0; 
  2733.  
  2734. /* make the table for a fast crc */
  2735. void make_crc_table(void)
  2736. {
  2737.   unsigned long c;
  2738.   int n, k;
  2739.  
  2740.   for (n = 0; n < 256; n++) {
  2741.     c = (unsigned long) n;
  2742.     for (k = 0; k < 8; k++)
  2743.       c = (c & 1) ? (0xedb88320L ^ (c >> 1)) : (c >> 1);
  2744.     crc_table[n] = c;
  2745.   }
  2746.   crc_table_computed = 1;
  2747. }
  2748.  
  2749. /* update a running crc with the bytes buf[0..len-1]--the crc should be
  2750.    initialized to all 1's, and the transmitted value is the 1's complement
  2751.    of the final running crc (see the crc() routine below)). */
  2752.  
  2753. unsigned long update_crc(unsigned long crc, unsigned char *buf, int len)
  2754. {
  2755.   unsigned long c = crc;
  2756.   unsigned char *p = buf;
  2757.   int n = len;
  2758.  
  2759.   if (!crc_table_computed)
  2760.     make_crc_table();
  2761.   if (n > 0) do {
  2762.     c = crc_table[(c ^ (*p++)) & 0xff] ^ (c >> 8);
  2763.   } while (--n);
  2764.   return c;
  2765. }
  2766.  
  2767. /* return the crc of the bytes buf[0..len-1] */
  2768. unsigned long crc(unsigned char *buf, int len)
  2769. {
  2770.   if (!crc_table_computed)
  2771.     make_crc_table();
  2772.   return update_crc(0xffffffffL, buf, len) ^ 0xffffffffL;
  2773. }
  2774.  
  2775. 13. Credits
  2776. ===========
  2777.  
  2778. Editor:
  2779. =======
  2780.  
  2781. Thomas Boutell, boutell@netcom.com 
  2782.  
  2783. Contributing Editor:
  2784. ====================
  2785.  
  2786. Tom Lane, tgl@sss.pgh.pa.us 
  2787.  
  2788. Authors:
  2789. ========
  2790.  
  2791. Authors' names are presented in alphabetical order. 
  2792.  
  2793.  o Mark Adler, madler@cco.caltech.edu 
  2794.  o Thomas Boutell, boutell@netcom.com 
  2795.  o Adam M. Costello, amc@cs.wustl.edu 
  2796.  o Lee Daniel Crocker, lee@piclab.com 
  2797.  o Oliver Fromme, fromme@rz.tu-clausthal.de 
  2798.  o Jean-Loup Gailly, jloup@chorus.fr 
  2799.  o Alex Jakulin, alex@hermes.si 
  2800.  o Neal Kettler, kettler@cs.colostate.edu 
  2801.  o Tom Lane, tgl@sss.pgh.pa.us 
  2802.  o Dave Martindale, davem@cs.ubc.ca 
  2803.  o Owen Mortensen, ojm@csi.compuserve.com 
  2804.  o Glenn Randers-Pehrson, glennrp@arl.mil 
  2805.  o Greg Roelofs, newt@uchicago.edu 
  2806.  o Paul Schmidt, photodex@netcom.com 
  2807.  o Tim Wegner, 71320.675@compuserve.com 
  2808.  o Jeremy Wohl, jeremy@cs.sunysb.edu 
  2809.  
  2810. The authors wish to acknowledge the contributions of the Portable
  2811. Network Graphics mailing list and the readers of comp.graphics. 
  2812.  
  2813. Trademarks
  2814. ==========
  2815.  
  2816. GIF is a service mark of CompuServe Incorporated. Macintosh is a
  2817. trademark of Apple Computer, Inc. Microsoft and MS-DOS are
  2818. trademarks of Microsoft Corporation. SGI is a trademark of Silicon
  2819. Graphics, Inc. X Window System is a trademark of the Massachusetts
  2820. Institute of Technology. 
  2821.  
  2822. End of PNG Specification 
  2823.